CORS in Node.js and AngularJS

落花浮王杯 提交于 2019-12-07 06:09:18

问题


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!


回答1:


Change -

res.header("Access-Control-Allow-Headers", "X-Requested-With");

TO

res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");

Source 1

Source 2




回答2:


I am posting same answer with a detailed code, Because i got some issues when i use the selected answer.

Just pull the code below after initialization of the app object

    app.all('/*', function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
      res.header("Access-Control-Allow-Methods", "GET, POST","PUT");
      next();
    });

I hope this will be little bit more helpful.



来源:https://stackoverflow.com/questions/25882106/cors-in-node-js-and-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!