CORS jQuery AJAX 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20442628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CORS jQuery AJAX request
提问by user6827
I'm having troubles with an ajax request. I was getting the error
我在处理 ajax 请求时遇到了麻烦。我收到错误
No 'Access-Control-Allow-Origin' header is present on the requested resource.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
So what I tried was this jQuery ajax request:
所以我尝试的是这个 jQuery ajax 请求:
var request = $.ajax({
type: 'GET',
url: url,
dataType: "json",
xhrFields: {
withCredentials: true
}
});
request.done(function(data){
console.log(data);
});
But it is still not working. I am still getting the error.
但它仍然无法正常工作。我仍然收到错误。
How should I fix this?
我应该如何解决这个问题?
回答by yoyo
It's easy, you should set server http response header first. The problem is not with your front-end javascript code.You need to return this header:
很简单,你应该先设置服务器http响应头。问题不在于您的前端 JavaScript 代码。您需要返回此标头:
Access-Control-Allow-Origin:*
or
或者
Access-Control-Allow-Origin:your domain
In Apache config files, the code is like this:
在Apache 配置文件中,代码是这样的:
Header set Access-Control-Allow-Origin "*"
In nodejs,the code is like this:
在nodejs中,代码是这样的:
res.setHeader('Access-Control-Allow-Origin','*');