本文介绍了Node.js和AngularJS中的CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的堆栈是Node.js,其中和AngularJS使用
我已经尝试了一些事情(),但我不断得到:
XMLHttpRequest无法加载http:// localhost:8080 / api / users。请求头字段Access-Control-Allow-Headers不允许Content-Type。
在服务器端我有这个标题:
{pre>
app.all('/ *',function(req,res,next){
res.header(Access-Control-Allow-Origin );
res.header(Access-Control-Allow-Headers,X-Requested-With);
res.header(Access-Control-Allow-Methods,GET ,POST,PUT);
next();
});
在AngularJS部分我正在使用:
$ httpProvider.defaults.useXDomain = true;
delete $ httpProvider.defaults.headers.common ['X-Requested-With'];
我正在用这样的Restangular做帖子:
var baseUsers = Restangular.all('users');
....
....
baseUsers.post(newUser).then(function(user){
console.log(user);
} );
还有一件事,在Node.js服务器中,我正在安慰 req 。方法
,它说选项
,我真的不知道为什么。
也许是愚蠢的,希望有人可以帮助我。
谢谢!
解决方案
更改 -
res.header(Access-Control-Allow-Headers,X-Requested-With );
TO
res.header(Access-Control-Allow-Headers,X-Requested-With,Content-Type);
I have a CORS problem with my app.
My stack is Node.js with Express 4 and AngularJS using Restangular
I already have tried a few things (for example) but I keep getting:
XMLHttpRequest cannot load http://localhost:8080/api/users. Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
In the server side I have this headers:
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "GET, POST","PUT");
next();
});
In the AngularJS part I am using this:
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
And I am doing the post with Restangular like this:
var baseUsers = Restangular.all('users');
....
....
baseUsers.post(newUser).then(function(user){
console.log(user);
});
One more thing, in the Node.js server I am consoling the req.method
and it says OPTIONS
, I really don't know why.
Perhaps is something silly, hope someone can help me.
Thanks!
解决方案
Change -
res.header("Access-Control-Allow-Headers", "X-Requested-With");
TO
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
这篇关于Node.js和AngularJS中的CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!