0

error happened

this is mylogin code : you can see the token from here and the next photo is the auth for token can anyone explain it please............................................................................................................................ verify token

    const login = (req, res, next) => {
    var username = req.body.username;
    var password = req.body.password;
    

    User.findOne({$or: [{email: username}, {phoneNumber: username}]})
    .then(user => {
        if (user) {
            bcrypt.compare(password, user.password, function(err, result){
                if (err) {
                    res.json({
                        title: 'Server error',
                        error: err
                    })
                    console.log('err');
                }if (result){
                    const maxAge = 24 * 60 * 60
          const createToken = jwt.sign({ _id: user._id } , process.env.TOKEN_SECRET, { expiresIn: maxAge });

              res.header('auth-token',token);

                    
                }else{
                    return res.status(401).json({
                        title: 'password wrong',
                        error: 'invalid credentials'
                    })
                }
            })
        }
        else {
            return res.status(401).JSON({
                title: 'password wrong',
                error: 'invalid credentials'
            })   
        }
    })
  • see similar question [Error: Can't set headers after they are sent to the client](https://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client) – turivishal Jun 01 '21 at 08:48

1 Answers1

0

If you look at the bcrypt.compare callback the res.json is executed twice:

  function(err, result) {
    if (err) {
      res.json({}) // ONE
    } 
    if (result) {
      // skipped
    } else {
      return res.status(401).json({ // TWO
        title: 'password wrong',
        error: 'invalid credentials'
      })
    }
  }

Add a return statement in the if(err)

Using a linter would help you to avoid these oversight

Manuel Spigolon
  • 11,003
  • 5
  • 50
  • 73