3

I'm getting a lot of Can't set headers after they are sent errors, and they never seem to give me line numbers in my app.js, is this normal? How do people debug these errors?

My code that is throwing the headers error looks like this, is it doing something weird to hide the line numbers?

app.get('/', function(req, res, next) {
    if (req.param('q')) {
        searchProvider.search(
            req.param('q'),
            function( error, results) {
                res.render('search', {
                    locals: {
                        results: results,
                        q: req.param('q')
                    },
                });
            }
        );
    } else {
        res.render('index');
    }
});
benui
  • 6,440
  • 5
  • 34
  • 49

1 Answers1

8

Can't set headers after they are sent

Is a common error which means your basically calling res.render, res.end or res.send multiple times. This means your trying to write multiple HTTP responses to one HTTP request (this is invalid).

A common cause of this bug is calling next twice in a piece of middleware.

Maybe you have a piece of middleware like

app.all("*", function(req, res, next) {
  // not logged in
  if (!req.user) {
    res.render("loginError");
  } 
  // bad accidental next call!! Will call next after rendering login error
  next();
});
Raynos
  • 166,823
  • 56
  • 351
  • 396