Chrome和Node Express JS Server的CORS问题

时间:2013-12-03 19:40:58

标签: express cors

我使用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();
});

当从浏览器发帖子时,这是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 GMT

POST请求标头:

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标题是我不确定的。

感谢。

1 个答案:

答案 0 :(得分:0)

我找到了一个我很满意的解决方案。

我在这个问题上把它放在这里:

CORS AngularJS Not Sending Cookie/Credentials with POST or DELETE but GET OK