Reputation: 36816
I have a pretty standard Node Express app with a global 404 handler like.
app.get('*', function(req, res){
res.status(404);
res.render('404page');
});
Now in some routes I have code like
app.get('/store/:product', function (req, res) {
if (productNotFound) return res.sendStatus(404);
});
What I would like is the res.sendStatus(404) to redirect to the error page WITHOUT having to change it to res.sendStatus(404).render('404page').
Is that possible?
Upvotes: 0
Views: 374
Reputation: 16127
Just override .sendStatus
of res
object.
Register this middleware right after creating the express app:
app.use((req, res, next) => {
const sendStatus = res.sendStatus.bind(res);
res.sendStatus = (status) => {
if (status === 404) {
return res.status(404).render('404page');
}
return sendStatus(status);
}
next()
});
Upvotes: 1