Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get Express.js to 404 only on missing routes?

At the moment I have the following which sits below all my other routes:

app.get('*', function(req, res){   console.log('404ing');   res.render('404'); }); 

And according to the logs, it is being fired even when the route is being matched above. How can I get it to only fire when nothing is matched?

like image 328
Hoa Avatar asked Jul 16 '12 07:07

Hoa


People also ask

How can I get 404 in Express?

All you need to do is add a middleware function at the very bottom of the stack (below all other functions) to handle a 404 response: app. use((req, res, next) => { res. status(404).

How do you protect Express routes?

The ensureAuthenticated function is just an example, you can define your own function. Calling next() continues the request chain. No idea, if you want to protect a set path you can use middleware e.g app. use('/user/*', ensureAuthenticated) will protect any matching routes.


1 Answers

You just need to put it at the end of all route.

Take a look at the second example of Passing Route Control:

var express = require('express')   , app = express.createServer();  var users = [{ name: 'tj' }];  app.all('/user/:id/:op?', function(req, res, next){   req.user = users[req.params.id];   if (req.user) {     next();   } else {     next(new Error('cannot find user ' + req.params.id));   } });  app.get('/user/:id', function(req, res){   res.send('viewing ' + req.user.name); });  app.get('/user/:id/edit', function(req, res){   res.send('editing ' + req.user.name); });  app.put('/user/:id', function(req, res){   res.send('updating ' + req.user.name); });  app.get('*', function(req, res){   res.send('what???', 404); });  app.listen(3000);  

Alternatively you can do nothing because all route which does not match will produce a 404. Then you can use this code to display the right template:

app.error(function(err, req, res, next){     if (err instanceof NotFound) {         res.render('404.jade');     } else {         next(err);     } }); 

It's documented in Error Handling.

like image 113
Charles Avatar answered Sep 24 '22 19:09

Charles