我试图在ajax的帮助下调用一个API。
$.ajax({
url:url,
type: 'POST',
data: JSON.stringify(data),
dataType: 'json',
async: false,
success: function(data, statusText, xhr) {
console.log("Calling success");
console.log(arguments);
console.log(data.status);
},
complete: function(data, statusText, xhr) {
console.log("Calling Complete");
console.log(arguments);
console.log(data.status);
},
error: function(data, statusText, xhr) {
console.log("Calling error");
console.log(arguments);
console.log(data.status);
}
});
调用ajax后,这是firefox中的响应:
您可以在图片中看到,我得到了200 statuscode
,在响应中,我得到了我的JSON数据。
下面是调用ajax后控制台的快照。
下面是错误对象:
Object { readyState: 0, getResponseHeader: .ajax/v.getResponseHeader(), getAllResponseHeaders: .ajax/v.getAllResponseHeaders(), setRequestHeader: .ajax/v.setRequestHeader(), overrideMimeType: .ajax/v.overrideMimeType(), statusCode: .ajax/v.statusCode(), abort: .ajax/v.abort(), state: .Deferred/d.state(), always: .Deferred/d.always(), then: .Deferred/d.then(), 11 more… }
挖掘对象后发现的错误:
Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'url I passed in ajax'. at Object.send (https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js:4:14955) at Function.ajax (https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js:4:10579) at HTMLButtonElement.<anonymous> (http://mywebsitestatic.s3-website-us-west-2.amazonaws.com/:258:4) at HTMLButtonElement.dispatch (https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js:3:6404) at HTMLButtonElement.r.handle (https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js:3:3179)
知道这个错误是什么吗。
我尝试过从stackoverflow.com中引用许多问题,但没有人与我的场景相匹配。有人能告诉我我哪里出了问题吗?
发布于 2016-12-19 13:37:31
这是一个Cross Origin Resource Sharing (CORS)
问题。要修复它,您必须在服务器中添加以下2个响应头(如果可以的话):
setHeader("Access-Control-Allow-Origin:", "origin url of your site");
setHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
要确认这是CORS
问题,您可以通过在chrome
中通过如下所示的控制台打开这个安全检查,并尝试使用url,
Windows:
chrome.exe --allow-file-access-from-files
chrome.exe --allow-file-access-from-files --disable-web-security
麦克:
open /Applications/Google\ Chrome.app/ --args --allow-file-access-from-files
注意事项:修复方法是在服务器中设置上面的响应头,您正试图从JQuery POST
请求中访问这些响应头。
AWS链接以启用CORS
http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html
References:(了解更多关于CORS
的信息)
同一原产地政策
https://stackoverflow.com/questions/41223212
复制相似问题