Javascript 获取请求未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33820142/
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
Getting request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
提问by Labeo
I am trying to send an Ajax request to a Tomcat server from my application, but I am getting this error (my web app is running on Chrome):
我正在尝试从我的应用程序向 Tomcat 服务器发送 Ajax 请求,但出现此错误(我的 Web 应用程序在 Chrome 上运行):
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403.
对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问 Origin 'null'。响应具有 HTTP 状态代码 403。
I have tried using
我试过使用
'Access-Control-Allow-Origin' : 'http://localhost:8080/app',
but it didn't work.
但它没有用。
My Ajax code:
我的 Ajax 代码:
var arr = [1];
$.ajax({
url: 'http://localhost:8080/app',
type: 'POST',
contentType:'application/json',
headers: {
'Access-Control-Allow-Origin' : 'http://localhost:8080',
},
data: JSON.stringify(arr[0]),
success: function(data){
//On ajax success do this
alert(data);
}
});
采纳答案by Chandan
Basically, to make a cross domain AJAX requests, the requested server should allow the cross origin sharing of resources (CORS). You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/
基本上,要进行跨域 AJAX 请求,请求的服务器应该允许跨源资源共享 (CORS)。您可以从这里阅读更多相关信息:http: //www.html5rocks.com/en/tutorials/cors/
In your scenario, you are setting the headers in the client which in fact needs to be set into http://localhost:8080/appserver side code.
在您的场景中,您正在客户端中设置标头,实际上需要将其设置为http://localhost:8080/app服务器端代码。
If you are using PHP Apache server, then you will need to add following in your .htaccess
file:
如果您使用的是 PHP Apache 服务器,则需要在.htaccess
文件中添加以下内容:
Header set Access-Control-Allow-Origin "*"
回答by L01c
In case of Request to a REST Service:
如果请求 REST 服务:
You need to allow the CORS (cross origin sharing of resources) on the endpoint of your REST Service with Spring annotation:
您需要使用 Spring 注释在 REST 服务的端点上允许 CORS(资源的跨源共享):
@CrossOrigin(origins = "http://localhost:8080")
Very good tutorial: https://spring.io/guides/gs/rest-service-cors/