我在使用AngularJS和Node ExpressJS服务器时遇到了Chrome CORS问题。
我读了很多关于这个问题的帖子,我已经实现了解决方案,但仍然没有什么乐趣。
希望另一双眼睛能看出我哪里错了。
我在开发本地机器,并且
From AngularJS app: http://localhost:3000
To Node ExpressJS Server : http://localhost:3001
Error is:
XMLHttpRequest cannot load http://localhost:3001/api/v1/articles.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:3000' is therefore not allowed access. 节点ExpressJS配置是标准推荐配置:
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
res.setHeader('Access-Control-Allow-Methods', 'POST,GET,PUT,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});在浏览器中执行post时,这是Chrome向服务器发出的飞行前请求:
请求头部:
OPTIONS /api/v1/articles HTTP/1.1
Host: localhost:3001
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:3000
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36
Access-Control-Request-Headers: accept, content-type
Accept: */*
Referer: http://localhost:3000/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8响应头部:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With
Access-Control-Allow-Methods:POST,GET,PUT,DELETE,OPTIONS
Access-Control-Allow-Origin:http://localhost:3000
Allow:GET
Connection:keep-alive
Content-Length:3
Content-Type:text/html; charset=utf-8
Date:Tue, 03 Dec 2013 19:24:22 GMTPOST请求头:
POST http://localhost:3001/api/v1/articles HTTP/1.1
Accept: application/json, text/plain, */*
Referer: http://localhost:3000/
Origin: http://localhost:3000
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36
Content-Type: application/json;charset=UTF-8然后出现控制台错误,并且无法开机自检。
服务器配置、飞行前选项请求和访问控制标头在我看来都是正确的。
你能看到一个问题吗?
OPTIONS响应中的Allow:GET头我不太确定。
谢谢。
发布于 2013-12-07 14:49:39
我找到了一个我很满意的解决方案。
我已经把它放在这个问题里了:
CORS AngularJS Not Sending Cookie/Credentials with POST or DELETE but GET OK
https://stackoverflow.com/questions/20360131
复制相似问题