I have an issue where a bad file request, css or images for example is getting caught by my 404 render. I really want to return a 404 response, but not render the 404 page in this case. In the past I've used nginx to handle file requests so this was not an issue. But what is the correct way to do this when express is handling file serving?
Here is my current route handling followed by error handling logic -
app.use(express.static(path.join(rootPath, 'public')));
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
// respond with html page
if (req.accepts('html')) {
res.render('404', { url: req.url });
return;
}
// respond with json
if (req.accepts('json')) {
res.send({ error: 'Not found' });
return;
}
// default to plain-text. send()
res.type('txt').send('Not found');
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message + " " + req.path,
error: err
});
});
}