我正在使用jQuery ajax将请求发送到某些API。由于有CORS政策,我在浏览器的控制台上收到了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);
});
未捕获的ReferenceError:未定义E0002,其中“ E0002”是来自api的响应字符串
!!!请帮忙!!!