1

I'm try to use express to build a simple website. everything it's works fine, until I decide to add a below code to catch 404 error

app.get('/*', function(req, res) {
 res.render('404.ejs',{
        title: 'PAGE NOT FOUND',
        layout:'layout'})
});

after that, notice all internal CSS file and JavaScript recourse file, not able to load correctly, I figure out because those CSS and JavaScript file ref link it's not inside the routing configure. That why all route to page not found which catch by /*

so just want to know, what is correct way, I can catch the 404 errors and display my own customize page, and also no impact on all resource file loading. Thanks!

Ringo
  • 3,795
  • 3
  • 22
  • 37
Yan Zhao
  • 185
  • 1
  • 8
  • 1
    Try to put this code at the end of files, after all other path and middleware declaration, more information here http://stackoverflow.com/questions/6528876/how-to-redirect-404-errors-to-a-page-in-expressjs – andbas Dec 04 '13 at 09:50
  • @andbas i have ready put at end of codes, the problem i thinks it's all my css file and js file are also reference link, which have not declare in the routing link, which case the error, all css and js file not able to load correctly. – Yan Zhao Dec 04 '13 at 10:00

1 Answers1

3

If you are using express, you should use error-handling middleware such as these examples:

// Routing and public files
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// Error-handling middleware
app.use(function(err, req, res, next) {
  // Parse error

  // Ex. if error = 500, render 500.jade page

  // At the end
  next(err);
});

// This is called on any page not in router.
app.use(function(req, res, next) {
  res.status(404);

  // respond with html page
  if (req.accepts('html')) {
    res.render('error/404', { title: '404 Error.' });
    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');
});

Refer to this For more information on Express error-handling.

Community
  • 1
  • 1
Xinzz
  • 2,242
  • 1
  • 13
  • 26