27

I have two routes in Express 4.13 app:

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

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

But when I'm trying to access /new - I get 404, because there is no 'new' object. So how can I change set up that I can access /new route without confusion with /:id route.

Thanks.

Erki M.
  • 5,022
  • 1
  • 48
  • 74
Nikita Unkovsky
  • 631
  • 1
  • 7
  • 13

2 Answers2

45

Do it like this . Dynamic api should be on bottom

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

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

A very simple example with test

Kasir Barati
  • 606
  • 13
  • 24
Ashutosh Jha
  • 15,451
  • 11
  • 52
  • 85
  • 1
    Simply moving the dynamic api methods below the static ones fixed my issues. Thanks! – user1653042 Nov 02 '20 at 22:56
  • I have one question though: what happens if I have a middleware after both routes? Does next() call the next handler or the handler that causes the conflict? – phramos07 Oct 28 '21 at 13:42
23

You need to add a function to check the parameter and place /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 () { })
stdob--
  • 28,222
  • 5
  • 58
  • 73