簡體   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