0

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
    });
  });
}
  • Can't you just look at what type of file is being requested and just do `res.status(404).end()` if it's the type of file you don't want to send back a 404 page for? – jfriend00 Mar 11 '17 at 18:51
  • I did not see any specific property of the request object that seemed obvious to use for this purpose. However, I suspect that the middleware must operate in a similar fashion. –  Mar 18 '17 at 18:41
  • `req.url` shows you the URL that was requested. You could look at the file extension at the end of the URL. – jfriend00 Mar 18 '17 at 19:26

1 Answers1

0

You could use the Express serve-static middleware: https://expressjs.com/en/resources/middleware/serve-static.html

Patrick Hund
  • 19,163
  • 11
  • 66
  • 95
  • Sorry I took so long to respond. I have used this middleware, however it does not include a redirect to a 404 page. For this I included this solution http://stackoverflow.com/questions/6528876/how-to-redirect-404-errors-to-a-page-in-expressjs –  Mar 18 '17 at 18:35