Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client in res.cookies

Viewed 65

I got the error my login router. I've looked at other solutions for this error, but none have applied to me.

The full error:

POST /login 404 30.803 ms - 145 node:internal/errors:477 ErrorCaptureStackTrace(err); ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at new NodeError (node:internal/errors:387:5) at ServerResponse.setHeader (node:_http_outgoing:603:11) at ServerResponse.header (dir\node_modules\express\lib\response.js:767:10) at ServerResponse.append (dir\node_modules\express\lib\response.js:728:15) at dir\node_modules\express\lib\response.js:853:8) at dir\routes\index.js:133:13 at processTicksAndRejections (node:internal/process/task_queues:96:5) { code: 'ERR_HTTP_HEADERS_SENT' }

I know it has something to do with res.cookies, but I can't for the life of me figure out which part of it is wrong.

router.post('/login', (req, res, next) => {
    const {email, password} = req.body;
    const hashedPassword = getHashedPassword(password);

    const findEmail = () => {
      return new Promise (function (resolve, reject) {connection.query(`SELECT * FROM users WHERE email = '${email}' AND pass = '${hashedPassword}'`, function (err, result, fields, callback) {
        // if any error while executing above query, throw error
        if (err) reject(err);
        // if there is no error, you have the result
        resolve(result);
      })});
    };

    function getResult() {
      return findEmail().then(function(response) {
          return response;
      })
    }
  
    getResult().then(function(result) {
      if (result.length > 0) {
        const authToken = generateAuthToken();

        // Store authentication token
        authTokens[authToken] = result;

        // Setting the auth token in cookies
        res.cookie('AuthToken', authToken), {maxAge: 900000};

        // Redirect user to the protected page
        res.redirect('/app/home');
        console.log(`User logged in: ${result.uname}, ${result.email}, ${result.password}`)
        return;
      }
      else
      {
        res.render('login', {
          message: 'Invalid username or password',
          messageClass: 'alert-danger'
        });
        return;
      }
    });
    next();
});

Edit: The error was caused by the next(); I was calling and had forgotten about.

0 Answers
Related