3

For every request that happens, I'd like to check if a parameter in the query string is set. If not, the application should send a certain message; otherwise, route as appropriate.

In app.js:

app.use(function(req,res,next){
    if(req.query.key === undefined) {
        res.send("Sorry!");
    }
    req.db = db;
    next();
});

app.use('/', routes);

When '/' is requested without the param, Sorry! is displayed. However, my ExpressJS app crashes with this error:

Error: Can't set headers after they are sent.

I'm not entirely sure why this is happening. I've tried moving the check to the route itself in index.js, but I still get the same error.

tverghis
  • 957
  • 8
  • 31

1 Answers1

8

That's because you're still continuing on with the execution and calling next(), which moves onto the next middleware or route in the stack.

Return early to stop it from moving onto the next middleware.

app.use(function(req,res,next){
    if(req.query.key === undefined) {
        //return out of the function here
        return res.send("Sorry!");
    }
    req.db = db;
    next();
});

app.use('/', routes);
Ben Fortune
  • 31,623
  • 10
  • 79
  • 80
  • Thanks, this worked. For some reason I assumed that `res.send()` was essentially equivalent to a return statement. – tverghis Jul 09 '15 at 13:20
  • 1
    @cmlndz In that case, `if(req.query.key)` is perfectly fine, no need for strict type checking. Plus the above method is valid, see http://stackoverflow.com/questions/4725603/variable-undefined-vs-typeof-variable-undefined Even if there's no query parameter, `req.query` is always defined. – Ben Fortune Jul 09 '15 at 13:39
  • @BenFortune you are right about req.query (perhaps I was dragging this from and old version of express). thnx – cmlndz Jul 09 '15 at 14:06