【问题标题】:POST body undefined causes node.js server to shutPOST body undefined 导致 node.js 服务器关闭
【发布时间】:2015-08-22 01:53:24
【问题描述】:

我通过 POST 将用户名和密码发送到 /user/login 路由上的 Node.js API。这是函数:

module.exports.login = function(req, res) {
    User.findOne({email: req.body.email}, function(err, user) {
        if(err) throw err;

        if(!user) {
            res.json({success: false, message: 'Invalid username or password!'});
        } else {
            if(!bcrypt.compareSync(req.body.password, user.password)) {
                res.json({success: false, message: 'Invalid username or password!'});
            } else {
                var token = jwt.sign(user, config.secret, {
                    expiresInMinutes: 1440
                });

                res.json({success: true, token: new Buffer(token).toString('base64')});
            }
        }
    });
}

为了获取帖子正文变量,我使用了 body-parser 模块。每当我发送没有电子邮件的 POST 请求时,req.body.email 返回undefined 并且猫鼬会在数据库中找到第一个用户(没有电子邮件验证)。

这很好,因为它会检查密码并返回错误消息。问题是,当req.body.passwordundefined 时,bcrypt.compareSync 返回一个错误,并且 node.js 会这样崩溃:

throw Error("Illegal arguments: "+(typeof s)+', '+(typeof hash));
Error: Illegal arguments: undefined, string

我可以先检查变量是否未定义,但必须有更好的方法来解决这个问题?

【问题讨论】:

    标签: javascript node.js post express body-parser


    【解决方案1】:

    如果电子邮件未定义,则不应执行登录功能的任何部分 - 如果自动选择数据库中的第一封电子邮件,则会出现重大安全漏洞。在传递给 API 函数之前检查值是否已定义实际上是处理问题的最佳方法。试试:

    module.exports.login = function(req, res) {
        if (req.body.hasOwnProperty('email') && req.body.hasOwnProperty('password')) {
            User.findOne({email: req.body.email}, function(err, user) {
                if(err) throw err;
                if(!user) {
                    res.json({success: false, message: 'Invalid username or password!'});
                } else {
                    if(bcrypt.compareSync(req.body.password, user.password)) {
                        var token = jwt.sign(user, config.secret, {
                            expiresInMinutes: 1440
                        });
                        res.json({success: true, token: new Buffer(token).toString('base64')});
                    } else {
                        res.json({success: false, message: 'Invalid username or password!'});
                    }
                }
            });
        }
    }
    

    【讨论】:

    • 我实际上已经在使用 js typeof 了。不知道 hasOwnProperty。谢谢。
    猜你喜欢
    • 2018-07-20
    • 2011-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    • 2013-10-21
    • 2011-07-12
    相关资源
    最近更新 更多