获取请求不会通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头 [英] Getting request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
问题描述
我正在尝试从我的应用程序向Tomcat服务器发送Ajax请求,但是我收到此错误(我的网络应用程序在Chrome上运行):
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):
对预检请求的响应未通过访问控制检查:请求的资源上没有Access-Control-Allow-Origin标头。因此不允许原点'null'访问。响应的HTTP状态代码为403.
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' : 'http://localhost:8080/app',
但它不起作用。
我的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);
}
});
推荐答案
基本上,为了制作跨域AJAX请求,请求的服务器应允许交叉源共享资源(CORS)。您可以从这里了解更多相关信息:
http://www.html5rocks.com / en / tutorials / cors /
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/
在您的方案中,您在客户端中设置标题,实际上需要将其设置为 http:// localhost:8080 / app 服务器端代码。
In your scenario, you are setting the headers in the client which in fact needs to be set into http://localhost:8080/app server side code.
如果您正在使用PHP Apache服务器,那么您需要在 .htaccess
文件中添加以下内容:
If you are using PHP Apache server, then you will need to add following in your .htaccess
file:
Header set Access-Control-Allow-Origin "*"
这篇关于获取请求不会通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!