我正在使用jQuery ajax向某个API发送请求。由于跨域资源共享策略,浏览器控制台显示CORS错误。
以下是我的代码
$.ajax({
url: sendHere,//api url
type: 'GET',
contentType: 'text/plain',
crossDomain: true,
beforeSend: function(xhr){
xhr.withCredentials = true;
},
}).done(function (result) {
console.log(result);
}).error(function (err) {
//console.log(err);
});
错误
请求的资源上存在'Access-Control-Allow-Origin'标头。因此,源'http://www.mywebsite.com'不允许访问。
我尝试通过安装Chrome扩展程序来解决这个问题以启用允许跨域请求。这个扩展程序在某种程度上解决了我的问题并从API获得了响应。但是安装扩展程序并不好。
我还尝试使用JSONP(dataType:'jsonp')发出请求,但是API返回的响应不是JSON格式,而是字符串,因此会出现错误。
JSONP代码
$.ajax({
url: sendHere,//api url
type: 'GET',
crossDomain: true,
dataType:'jsonp',
}).done(function (result) {
console.log(result);
}).error(function (err) {
//console.log(err);
});
未捕获的引用错误:E0002未定义,其中“E0002”是来自API的响应字符串
!!!请帮忙!!!
console.log(result)
语句更改为console.log(JSON.stringify(result))
时会发生什么? - David Rtype: 'GET'
并将contentType
从contentType: 'text/plain',
更改为contentType: 'application/json',
,并使用一个在此处正常工作的 Web 服务测试了代码 => https://jsfiddle.net/9pqhwrpv/2/ - David R