4

何らかの理由で、API サーバーにデータを投稿しようとすると、次の 2 つのエラーが発生します。

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. 

これは、いくつかの単純なデータを送信しようとしているクライアント側の角度のある JS コードです。このコードは現在、次の場所にある nginx サーバーで実行されています。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');
            });
    };
    }

リクエストを「処理」するノード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);
});
4

1 に答える 1

10

エラー メッセージに示されているように、プリフライトへの応答で Content-Type ヘッダーを確認する必要があります。これは、リクエストの Content-Type が「単純」ではないことが原因である可能性があります (表向きは application/json)。

したがって、これの代わりに:

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

...あなたはこれを必要とします:

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

于 2013-11-08T20:21:36.730 に答える