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?
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'.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With