【发布时间】:2016-11-10 06:11:42
【问题描述】:
我正在使用 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”标头出现在请求的资源上。 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);
});
Uncaught ReferenceError: E0002 is not defined 其中“E0002”是来自 api 的响应字符串
!!!请帮忙!!!
【问题讨论】:
-
将
console.log(result);语句更改为console.log(JSON.stringify(result));时会发生什么 -
@DavidR 即使在 console.log(JSON.stringify(result)) 上也会发生错误
-
您可以尝试在您的
dataType: 'jsonp',语句后添加jsonp: 'callback',吗? -
我已删除
type: 'GET'并将contentType从contentType: 'text/plain',更改为contentType: 'application/json',并使用在这里运行良好的 web 服务测试代码 => jsfiddle.net/9pqhwrpv/2
标签: javascript jquery json ajax api