express js send 404 code with * route code example
Example 1: express 404
app.get('*', function(req, res, next) {
var err = new Error();
err.status = 404;
next(err);
});
app.use(function(err, req, res, next) {
if (err.status === 404) {
var data = {
title: '404 Not Found',
content: 'Oops, page not found!';
};
res.render('pages/404', data);
} else {
return next();
}
});
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');
});