我收到这个 JavaScript 错误
XMLHttpRequest cannot load http://foo.bar.no/API/map_tools/clean_addresses/check. Origin http://foo.bar.no:9294 is not allowed by Access-Control-Allow-Origin.
这一切都在同一个域和同一台服务器上,但我的 JavaScript 项目由一个独立的服务器脚本托管,该脚本自动将 JavaScript 及其依赖项捆绑到一个文件中。
我在开发时如何突破这个限制?
我已尝试允许我的 JavaScript 服务器脚本进行连接。这是 url curl 的结果:
HTTP/1.1 200 OK Date: Wed, 11 Jan 2012 09:05:14 GMT Server: Apache/2.2.16 (Debian) Access-Control-Allow-Origin: http://foo.bar.no:9294 Vary: Accept-Encoding Content-Length: 70 Content-Type: text/plain array(1) { ["q"]=> string(31) "map_tools/clean_addresses/check" }
而且我仍然得到与上面粘贴的完全相同的错误。为什么 Chrome 在明显允许的情况下仍然拒绝连接到该死的 URL!?
最佳答案
好吧,我明白了。我一直在寻找一个简单快速的修复方法,因为我只需要跨域请求用于开发目的。结果我只需要同时设置这两个
header("Access-Control-Allow-Origin: http://foo.bar.no:9294");
header("Access-Control-Allow-Credentials: true");
在我在 Apache 上的 PHP 脚本中。然后在我的 JavaScript 代码中:
# Set jQuery ajax to use 'withCredentials' globally
$.ajaxSetup({
xhrFields: {
withCredentials: true
}
});
这就成功了
关于javascript - 有什么方法可以通过 Access-Control-Allow-Origin 在我自己的服务器上进行开发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8816487/