触发 AJAX GET
到 http://qualifiedlocalhost:8888/resource.json
会启动预期的 CORS 预飞行,看起来它会正确返回:
飞行前OPTIONS
请求
Request URL:http://qualifiedlocalhost:8888/resource.json
Request Method:OPTIONS
Status Code:200 OK
请求 header
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, origin, x-requested-with
Access-Control-Request-Method:GET
Cache-Control:no-cache
Connection:keep-alive
Host:qualifiedlocalhost:8888
Origin:http://localhost:9000
Pragma:no-cache
Referer:http://localhost:9000/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36
响应 header
Access-Control-Allow-Headers:Content-Type, X-Requested-With
Access-Control-Allow-Methods:GET,PUT,POST,DELETE
Access-Control-Allow-Origin:*
Connection:keep-alive
Content-Length:2
Content-Type:text/plain
Date:Thu, 01 Aug 2013 19:57:43 GMT
Set-Cookie:connect.sid=s%3AEpPytDm3Dk3H9V4J9y6_y-Nq.Rs572s475TpGhCP%2FK%2B2maKV6zYD%2FUg425zPDKHwoQ6s; Path=/; HttpOnly
X-Powered-By:Express
看起来不错?
所以它应该有效,对吧?
但是后续请求仍然失败,错误XMLHttpRequest cannot load http://qualifiedlocalhost:8888/resource.json。 Access-Control-Allow-Origin 不允许来源 http://localhost:9000。
真实请求
Request URL:http://qualifiedlocalhost:8888/resource.json
请求 header
Accept:application/json, text/plain, */*
Cache-Control:no-cache
Origin:http://localhost:9000
Pragma:no-cache
Referer:http://localhost:9000/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36
X-Requested-With:XMLHttpRequest
救命!
也许它就在我面前凝视着。但是,有什么想法吗?以防万一它是相关的......我正在使用 AngularJS $resource
并与 CompoundJS 服务器交谈。
最佳答案
将您的 Access-Control-Allow-Methods: 'GET, POST' 更改为 'GET, POST, PUT, DELETE'
之前:
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
next();
});
之后:
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT ,DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
next();
});
关于javascript - CORS 飞行前返回 Access-Control-Allow-Origin :*, 浏览器仍然失败请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18003605/