Express parameterized conflict route

I have two routes in Express 4.13 application:

router.get('/:id', function (req, res) { }); router.get('/new', function(req,res){ }); 

But when I try to access /new , I get 404 because there is no new object. So, how can I change the settings so that I can access / the new route without confusing the route /: id.

Thanks.

+7
express routing
source share
2 answers

You need to add a function to check the parameter and place the /new router before /:id :

 var express = require('express'), app = express(), r = express.Router(); r.param('id', function( req, res, next, id ) { req.id_from_param = id; next(); }); r.get("/new", function( req, res ) { res.send('some new'); }); // route to trigger the capture r.get('/:id', function (req, res) { res.send( "ID: " + req.id_from_param ); }) app.use(r); app.listen(3000, function () { }) 
+6
source share

Do it like that. Dynamic api should be at the bottom

 router.get('/new', function(req,res){ }); router.get('/:id', function (req, res) { }); 
+8
source share

All Articles