express js 404 page code example
Example 1: how to handle all error of all router in express
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error.ejs', {
message: err.message,
error: err
});
});
}
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
Example 2: set 404 handling via express in node
app.use(function(req, res, next){
res.status(404);
if (req.accepts('html')) {
res.render('404', { url: req.url });
return;
}
if (req.accepts('json')) {
res.send({ error: 'Not found' });
return;
}
res.type('txt').send('Not found');
});
Example 3: node express dynamic route and error handler
app.use(function (req, res, next) {
res.status(404).send("Sorry can't find that!")
})