我正在使用 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);
});
Run Code Online (Sandbox Code Playgroud)
错误
请求的资源上存在“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);
});
Run Code Online (Sandbox Code Playgroud)
未捕获的引用错误:未定义 E0002,其中“E0002”是来自 api 的响应字符串
!!!请帮忙!!!