简体   繁体   English

在Node.js中处理CORS

[英]Handling CORS in Node.js

I have two applications, both running on different instances of Node server, but on the same machine. 我有两个应用程序,它们都在节点服务器的不同实例上运行,但是在同一台计算机上。

The server's server.js : 服务器的server.js

app.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST', 'OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');

    // intercept OPTIONS method
    if ('OPTIONS' == req.method) {
        console.log('Inside options');
      res.send(200);
    }
    else {
        console.log('Inside others');
      next();
    }
});

app.post('/signin', function(req, res) {
    console.log('signin called');
    User.findOne({email: req.body.email, password: req.body.password}, function(err, user) {
        if (err) {
            console.log('err');
            res.json({
                type: false,
                data: "Error occured: " + err
            });
        } else {
            if (user) {
                console.log('User exists');
                res.json({
                    type: false,
                    data: "User already exists!"
                });
            } else {
                console.log('inside create user');
                var userModel = new User();
                userModel.email = req.body.email;
                userModel.password = req.body.password;
                userModel.save(function(err, user) {
                    user.token = jwt.sign(user, process.env.JWT_SECRET);
                    user.save(function(err, user1) {
                        res.json({
                            type: true,
                            data: user1,
                            token: user1.token
                        });
                    });
                })
                console.log('create user ends');
            }
        }
    });
});

On the client, controller.js : 在客户端上, controller.js

    $scope.signup = function() {
                var formData = {
                    email: $scope.email,
                    password: $scope.password
                }

                Main.save(formData, function(res) {
                    console.log('response received from service');
                    if (res.type == false) {
                        alert(res.data)
                    } else {
                        $localStorage.token = res.data.token;
                        window.location = "/"    
                    }
                }, function() {
                    $rootScope.error = 'Failed to signup';
                })
            };

And services: 和服务:

    return {
                save: function(data, success, error) {
                    console.log('signin request sent');
                    $http.post(baseUrl + '/signin', data).success(success).error(error)
                    console.log('signin response received');
                },
                signin: function(data, success, error) {
                    $http.post(baseUrl + '/authenticate', data).success(success).error(error)
                },
                me: function(success, error) {
                    $http.get(baseUrl + '/me').success(success).error(error)
                },
                logout: function(success) {
                    changeUser({});
                    delete $localStorage.token;
                    success();
                }
            };

When I call the signup method from client, server console prints this: 当我从客户端调用signup方法时,服务器控制台将输出以下内容:

Inside options
OPTIONS /signin 200 12.110 ms - 3
Inside others
signin called
inside create user
create user ends
POST /signin - - ms - -
Inside others
signin called
User exists
POST /signin 200 15.309 ms - 44

What is happening that browser first sends the OPTIONS request, which is responded with a 200 status code, then a POST request is sent which creates the user but client doesn't get the response. 发生了什么情况,浏览器首先发送OPTIONS请求,并以200状态码响应,然后发送POST请求,该请求创建了用户,但客户端未获得响应。 Another POST request with the same data is sent by the browser but by then user is already created and server returns a user already exists message. 浏览器会发送另一个具有相同数据的POST请求,但是到那时,已经创建了用户,服务器返回了一个用户已经存在的消息。

I am not able to find the reason for it. 我找不到原因。

Edit: I don't think it's due to CORS at all. 编辑:我根本不认为这是由于CORS。 I used cars package, and added a app.use(cos()) at the top in server.js. 我使用汽车包装,并在server.js的顶部添加了一个app.use(cos())。 After that the server console prints - 之后,服务器控制台将打印-

signing called inside create user create user ends POST /signin - - ms - - signing called User exists POST /signin 200 32.007 ms - 44 签名在内部创建用户创建用户创建用户端POST /登录--ms--签名被称为用户存在POST /登录200 32.007 ms-44

I think something is getting stuck at server end, and therefore client is sending the request again. 我认为服务器端有些卡住,因此客户端再次发送了请求。

有些防火墙会部分阻止CORS,最佳做法是通过https使用CORS

I guess the problem is with the header. 我猜问题出在标题上。 Please add following header while making the POST call : 在进行POST调用时,请添加以下标头:

'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'

I have had the similar problem once and it just worked out after adding this header in the POST call. 我曾经有过类似的问题,并且在POST调用中添加了此标头后才解决。

Hope this works :) 希望这有效:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM