Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express parameterized route conflict

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.

like image 993
Nikita Unkovsky Avatar asked Jul 18 '15 16:07

Nikita Unkovsky


2 Answers

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

like image 168
Ashutosh Jha Avatar answered Nov 11 '22 08:11

Ashutosh Jha


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 () { })
like image 23
stdob-- Avatar answered Nov 11 '22 08:11

stdob--