繁体   English   中英

node.js无法使用res.json设置标头错误

[英]node.js cannot set header error using res.json

if (user) {

    if (userId != user._id) {
        res.json({success: false, msg: 'Invalid request, wrong secret key'});
    }

    User.comparePassword(password, user.password, function (err, result) {
        if (result === true) {

            res.json({success: true, msg: 'ok'});
        } else {
            res.json({success: false, msg: 'Error, Incorrect password!'});
        }
    });
} else {
    res.json({ success: false, msg: 'Error, account not exist!'});
}

我以为第一个res.json将停止随后的res.json,但是在这种情况下,我似乎无法使用第一个res.json,我不知道为什么。

res.json()发送响应,但不会阻止其余代码运行。

这样,您就有一些代码路径尝试发送两次res.json() ,这将导致您看到的错误消息。 您需要通过适当的if/then块或插入适当的return语句来防止这种情况。

我建议这样做:

if (user) {

    if (userId != user._id) {
        res.json({success: false, msg: 'Invalid request, wrong secret key'});
        return;
    }

    User.comparePassword(password, user.password, function (err, result) {
        if (result === true) {

            res.json({success: true, msg: 'ok'});
        } else {
            res.json({success: false, msg: 'Error, Incorrect password!'});
        }
    });
} else {
    res.json({ success: false, msg: 'Error, account not exist!'});
}

但是,您还可以通过在第一个if添加else并将其余代码放入其中来修复它。

暂无
暂无

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

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