首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Chome和节点ExpressJS服务器的CORS问题

问Chome和节点ExpressJS服务器的CORS问题
EN

Stack Overflow用户
提问于 2013-12-04 03:40:58
回答 1查看 1.1K关注 0票数 2

我在使用AngularJS和Node ExpressJS服务器时遇到了Chrome CORS问题。

我读了很多关于这个问题的帖子,我已经实现了解决方案,但仍然没有什么乐趣。

希望另一双眼睛能看出我哪里错了。

我在开发本地机器,并且

代码语言:javascript
复制
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配置是标准推荐配置:

代码语言:javascript
复制
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向服务器发出的飞行前请求:

请求头部:

代码语言:javascript
复制
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

响应头部:

代码语言:javascript
复制
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请求头:

代码语言:javascript
复制
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头我不太确定。

谢谢。

EN

回答 1

Stack Overflow用户

发布于 2013-12-07 14:49:39

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

我已经把它放在这个问题里了:

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20360131

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档