Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

catch all routes in expressjs

Tags:

express

routes

I'd like to set some catch all routes in expressjs

I have three levels

/module

/module/page

If module route does not exist send to 404 route equally if the module exists but the page doesn't send to 404 route.

404 replies in html

/api/controller/method

As above, but 404 equivalent would reply in json

Regex is killing me so if any one can help me out my hairline would much appreciate it. :) I've thought of using a route look-up table but I want to try and do it the 'express' way.

like image 832
Chin Avatar asked Jan 18 '26 01:01

Chin


1 Answers

Just set up the routes for /module /module/page (or maybe you wanted something like /module/:page_id)

and at the bottom of all routes you want to add

 app.use(function(req,res) { 
    res.render('404', 
               { locals: {'title':'Not Found'}, }, 
               function(err,str) { res.send(str,404); } ); 

if nothing matches the catch all snaps!

this is from that thread over in the google groups https://groups.google.com/forum/?fromgroups=#!topic/express-js/aYLM4e1I4XU

like image 130
silverfighter Avatar answered Jan 21 '26 05:01

silverfighter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!