When I uncomment one line of code, I receive this error: _http_outgoing.js:359 throw new Error('Can\'t set headers after they are sent.');

前端 未结 1 1510
梦毁少年i
梦毁少年i 2021-01-26 07:26

When I uncomment this line: return done(null, false, { message: \'Incorrect username\' }); in the following code, Node.js runs without any error, otherwise, Node.js

相关标签:
1条回答
  • 2021-01-26 07:41

    That error message is caused by a timing error in the handling of an async response that causes you to attempt to send data on a response after the response has already been sent.

    It usually happens when people treat an async response inside an express route as a synchronous response and they end up sending data twice.

    You should add else in your statement

    if (password !== user.password) {
       return done(null, false, { message: 'Incorrect password' });
    } else {
        return done(null, user);
    }
    

    Update:

    function UserFind(username, cb) {
        var userFound = false, userVal = "";
        db.view('users/by_username', function(err, res) {
            if (err) {
                //db.view returned error
                return cb(err);
            }
            res.forEach(function(key, value, id) {
                    //1st input=key|username, 2nd input=value|userDocument, 3rd input=id|_id
                    //console.log('key: '+key+' row: '+row+' id: '+ id);
                    if (username === key) {
                        //found the user
                        userFound = true;
                        userVal = value;
                    }
                });
    
           if (userFound) {
              return cb(false, userVal);
           } else {
             // User did not found
             return cb(false, false);
           }
        })
    }
    
    0 讨论(0)
提交回复
热议问题