简体   繁体   中英

NodeJS Cannot set headers error when I'm not setting any

I have a middleware function to check to make sure that the user is logged in on each page load like this

app.use(function(req, res, next) {
  if (req.cookies.hasOwnProperty('rememberToken')) {
    app.get('db').Users.find({'rememberToken': req.cookies.rememberToken}, function(errFind, resultsFind) {
      if (errFind) {
        return next();
      } else if (resultsFind.length === 0) {
        return next();
      }
      app.locals.isLoggedIn = true;
      app.locals.username   = resultsFind[0].user_username;
      return next();
    });
  } else if (req.session.hasOwnProperty('isLoggedIn')) {
      app.locals.isLoggedIn = true;
      app.locals.username   = req.session.username;
      console.log(app.locals);
      return next();
  }
  return next();
});

The only problem is when it's doing the cookie auth I get this error:

GET / 500 3ms
Error: Can't set headers after they are sent.

I have narrowed it down within the function that the error is coming from

app.get('db').Users.find({'rememberToken': req.cookies.rememberToken}, function(errFind, resultsFind) {

});

If I remove this function the error goes away, I'm not sure why using this function is causing this error can anybody help me out here. I have this line of middleware before my routes in app.js

This is due to the asyncronous nature of node.js. On the very last line of the function you have a return next() that passes the request to the next middleware. This means that the headers have been sent.

When you include the function, the database is called but the server carries on so that your server can handle other requests while it waits for the database to return your user. When your database does return with the data then it steps inside your callback function where it tries to execute return next() . But in your case next has already been called, and that is why you get the error.

To solve this, remove the return next() on the last line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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