tverghis
tverghis

Reputation: 999

ExpressJS - Send a response from middleware

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.

Upvotes: 5

Views: 6945

Answers (1)

Ben Fortune
Ben Fortune

Reputation: 32118

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);

Upvotes: 9

Related Questions