Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using multiple router in express

I've applied the routes to my application like this:

var express = require('express');
var app = express();
var router = express.Router();

  //localhost:8080/api/story
router.get('/story', function(req, res){
    res.send('welcome to our story');
})

  //localhost:8080/api
app.use('/api', router); 

  //localhost:8080/user/02213
router.get('/user/:id', function(req , res){ 
  console.log(req.params.id);
});

localhost:8080/user/02213 not working at the moment. Do I need to create a new router instead or?

like image 614
Sahin Erbay Avatar asked May 09 '17 18:05

Sahin Erbay


People also ask

How do I add a router to Express?

To use the router module in our main app file we first require() the route module (wiki. js). We then call use() on the Express application to add the Router to the middleware handling path, specifying a URL path of 'wiki'.

Can a request have two same routes?

As for having two routes concurrently matching parameters at the root level, that's just impossible as the first route defined will receive all incoming requests, while the second will receive none, simply because there is no way to tell a :session parameter from a :name parameter.

What is router () in Express?

The express. Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests. Multiple requests can be easily differentiated with the help of the Router() function in Express. js.


1 Answers

Yes, you need to create a new router, because router will only be used for requests that start with /api:

//localhost:8080/api/story
router.get('/story', function(req, res){
  res.send('welcome to our story');
})

//localhost:8080/api
app.use('/api', router); 

//localhost:8080/user/02213
var anotherRouter = express.Router();
anotherRouter.get('/user/:id', function(req , res){ 
  console.log(req.params.id);
  res.end();
});
app.use('/', anotherRouter);
like image 155
robertklep Avatar answered Oct 04 '22 03:10

robertklep