CORS in Node.js and AngularJS

I have a problem with CORS with my application.

My Node.js stack with Express 4 and AngularJS using Restangular

I have already tried several 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.

On the server side, I have the following 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 use this:

$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];

And I am doing a message with Restangular as follows:

var baseUsers = Restangular.all('users');
....
....
baseUsers.post(newUser).then(function(user){
console.log(user);
});

One more thing, on the Node.js server, I console req.method, and he says OPTIONS, I really don't know why.

Perhaps this is something stupid, I hope someone can help me.

Thank!

+4
source share
2 answers

Edit -

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

TO

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

1

2

+1

, , .

app

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

, .

0

All Articles