使用Node.js和AngularJS遇到CORS问题

4
由于某种原因,每当我尝试向我的API服务器发布一些数据时,我会收到以下两个错误。
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. 

这是我的客户端angular JS代码,试图发送一些简单的数据。此代码当前正在运行位于http://localhost:8080下的nginx服务器上。

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

以下是我用 Node.js 编写的代码,用于处理请求到 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);
});
1个回答

10
根据错误信息所述,您必须在响应预检请求中确认Content-Type标头。这可能是由于您的请求具有非“简单”Content-Type(似乎是application/json)引起的。
因此,您需要使用以下代码替换:
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
而不是原来的代码:
res.header("Access-Control-Allow-Headers", "X-Requested-With");

太棒了,那正是我所需要的。 - Austin Davis
我将引号放错位置了,这让我头疼了一个小时 -- 请注意"X-Requested-With, Content-Type"是一个参数。 - Jake

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接