4

For some reason whenever I try to post some data to my api server I get the following two errors.

OPTIONS http://localhost:3000/test2 Request header field Content-Type is not allowed by Access-Control-Allow-Headers. angular.min.js:99
XMLHttpRequest cannot load http://localhost:3000/test2. Request header field Content-Type is not allowed by Access-Control-Allow-Headers. 

Here is my client side angular JS code trying to send some simple data. This code is currently running on an nginx server located under http://localhost:8080

function Controller($scope, $http) {
    //scope is all of the elements within the controller declared on the html
    var url = 'http://localhost:3000/test2';

    $scope.listVaules = function () {
        console.log("about to post user id");
        console.log($scope.user.userId);
        console.log($scope.user.name);
        console.log($scope.user.password);
        console.log(JSON.stringify($scope.user));
        $http({ method: 'Post', url: url, data: JSON.stringify($scope.user) }).
            success(function (data, status, headers, config) {
                console.log(data);
                console.log('success');
            }).
            error(function (data, status, headers, config) {
                console.log('error');
            });
    };
    }

Here is my node JS code to handle that "handles" the request to localhost:3000/test2

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

//Should post client side json info to the server
app.post(url + '/test2', function(req, res) {
    var name = req.body.name;
    var userId = req.body.userId;
    var password = req.body.password;

    console.log(name + ' ' + userId + ' ' + password);
    res.send(200);
});
0

1 Answer 1

10

As the error message states, you must acknowledge the Content-Type header in your response to the preflight. This is likely caused by a non-"simple" Content-Type for your request (ostensibly application/json).

So, instead of this:

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

...you need this:

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

Sign up to request clarification or add additional context in comments.

2 Comments

awsome that was exactly what I needed
I had the quotes in the wrong place and it caused me an hour of headache -- be sure to notice "X-Requested-With, Content-Type" is one argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.