简体   繁体   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!'});
}

I thought the first res.json will stop the following res.json but in this case I seem can't use the first res.json, I don't know why. 我以为第一个res.json将停止随后的res.json,但是在这种情况下,我似乎无法使用第一个res.json,我不知道为什么。

res.json() sends the response, but it does not prevent the rest of your code from running. res.json()发送响应,但不会阻止其余代码运行。

As such, you have some code paths that attempt to send res.json() twice which will cause the error message you are seeing. 这样,您就有一些代码路径尝试发送两次res.json() ,这将导致您看到的错误消息。 You need to prevent that either with appropriate if/then blocks or by inserting appropriate return statements. 您需要通过适当的if/then块或插入适当的return语句来防止这种情况。

I'd suggest this: 我建议这样做:

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

But, you also could fix it by adding an else to the first if and putting the rest of the code inside that. 但是,您还可以通过在第一个if添加else并将其余代码放入其中来修复它。

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

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