nodejs和AngularJS的CORS问题 [英] CORS trouble with nodejs and AngularJS

查看:16
本文介绍了nodejs和AngularJS的CORS问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因,每当我尝试将一些数据发布到我的 api 服务器时,我都会收到以下两个错误.

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. 

这是我试图发送一些简单数据的客户端 Angular JS 代码.此代码当前在位于 http://localhost:8080

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

这是我的节点 JS 代码,用于处理处理"对 localhost:3000/test2

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

推荐答案

正如错误消息所述,您必须在对预检的响应中确认 Content-Type 标头.这可能是由您的请求的非简单"Content-Type(表面上是 application/json)引起的.

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).

所以,不要这样:

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

...你需要这个:

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

这篇关于nodejs和AngularJS的CORS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆