我正在尝试使用CORS在我的浏览器和Apache服务器(位于不同的域)之间运行AJAX请求。
在服务器端,我在httpd中做了以下更改。根据“Header set Access Control Allow Origin in.htaccess不工作”中的响应配置服务器的部分:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
我的AJAX调用的形式如下:
$.ajax({
url :'https://x.x.x.x/validateCustomerID',
type : 'POST',
cache : false,
crossDomain: true,
contentType: 'application/json',
beforeSend: function(xhr){
xhr.setRequestHeader("Access-Control-Allow-Methods","POST");
xhr.setRequestHeader("Access-Control-Allow-Headers","X-Requested-With");
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
},
data : {loginId : '12345'},
success : function(response){console.log("Success"+JSON.stringify(response))},
error : function(response){console.log("Error"+JSON.stringify(response))}
});
}
我还尝试注释beforeSend()以避免飞行前请求,但也没有成功。
我在Chrome和火狐上收到的错误信息是:
"XMLHttpRequest无法加载https://x. x. x. x/validateCustomer ID。请求的资源上没有访问-控制-允许-起源标头。因此,不允许访问源'null'。响应具有HTTP状态代码403。"
“阻止跨源请求:同一源策略不允许读取位于的远程资源。”https://x.x.x.x/validateCustomerID.(原因:CORS请求失败)。"
在我的浏览器中没有收到来自服务器的响应头,我认为这是CORS工作所必需的,并且服务器中的日志显示没有从我的浏览器到达它的请求。
如果这里有人能帮我解决这个问题,我会非常感激,因为我已经在这里呆了好几天了,并且已经使用了几乎所有的点击和试用方法来实现这个目标。
这是我在site.conf
中的设置,它现在在apache2的生产中工作
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "authorization, origin, user-token, x-requested-with, content-type"
Header set Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
为了将来的参考,我强烈建议书签这个网站http://enable-cors.org/index.html