尽管我为服务器(nginx/node.js)设置了适当的头,但我仍然被这个CORS问题所困扰。
我可以在Chrome网络窗格->响应标题中看到:
Access-Control-Allow-Origin:http://localhost
这应该能起到作用。
下面是我现在用来测试的代码:
var xhr = new XMLHttpRequest();
xhr.onload = function() {
console.log('xhr loaded');
};
xhr.open('GET', 'http://stackoverflow.com/');
xhr.send();
我得到了
XMLHttpRequest无法加载http://stackoverflow.com/。access-control-allow-origin不允许Origin http://localhost。
我怀疑是客户端脚本的问题,而不是服务器配置的问题...
Chrome不支持CORS请求的localhost(2010年发现的一个漏洞,2014年标记为WontFix)。
要解决这个问题,您可以使用lvh.me
这样的域(它与localhost一样指向127.0.0.1),或者使用--disable-web-security
标志启动chrome(假设您只是在测试)。