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

node.js cannot set header error using res.json

本文关键字:设置 json 错误 res js 节点      更新时间:2023-09-26
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并将其余代码放入其中来修复它。