Express router -: id?

Real simple guys: I see that many book fragments / code fragments use the following syntax in the router:

app.use('/todos/:id', function (req, res, next) { console.log('Request Type:', req.method); next(); }); 

I'm not sure how to interpret the route here ... will it route '/ todos / anything'? and then grab anything, and the treatment with a variable identifier? how to use this variable? I am sure this is a quick answer, I just have not seen this syntax before.

+11
express
source share
4 answers

This is a common middleware.

In this case, yes, it will send /todos/anything , and then req.params.id will be set to 'anything'

+12
source share

In your code intended for middleware Express Framework, if you want to get any identifier in the server code using this route, you will get this identifier using req.params.id .

 app.use('/todos/:id', function (req, res, next) { console.log('Request Id:', req.params.id); next(); }); 
+13
source share

Yes, in your example you will get req.params.id value of "nothing"

+2
source share
 Route path: /student/:studentID/books/:bookId Request URL: http://localhost:xxxx/student/34/books/2424 req.params: { "studentID": "34", "bookId": "2424" } app.get('/student/:studentID/books/:bookId', function (req, res) { res.send(req.params); }); 

Similarly for your code:

 Route path: /todos/:id Request URL: http://localhost:xxxx/todos/36 req.params: { "id": "36" } app.use('/todos/:id', function (req, res, next) { console.log('Request Id:', req.params.id); next(); }); 
0
source share

All Articles