47

Real simple question guys: I see a lot of books/code snippets 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 the 'anything' and treat is at variable ID? how do I use that variable? I'm sure this is a quick answer, I just haven't seen this syntax before.

glog
  • 809
  • 2
  • 9
  • 19

6 Answers6

48

This is an express middleware.

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

Rilke Petrosky
  • 1,155
  • 9
  • 12
24

On your code, that is for express framework middleware, if you want to get any id in the server code using that route, you will get that id by req.params.id.

app.use('/todos/:id', function (req, res, next) {
  console.log('Request Id:', req.params.id);
  next();
});
shivangg
  • 521
  • 8
  • 15
Md Nazmul Hossain
  • 2,768
  • 5
  • 26
  • 49
4
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();
});
Pingolin
  • 3,161
  • 6
  • 25
  • 40
Roshan
  • 571
  • 4
  • 4
2

Yes, in your example youl get req.params.id set to 'anything'

Nir Levy
  • 12,750
  • 3
  • 21
  • 38
1

A bit late to the party but the question mark in your question made me think of something that hasn't been touched upon.

If your route had a question mark after the id like so: '/todos/:id?', id would be an optional parameter, meaning you could do a getAll() if id was omitted (and therefore undefined).

Sven Cazier
  • 397
  • 4
  • 12
0

This is called Path params and it's used to identify a specific resource.

and as all answer how to get the value of the path params

app.use('/todos/:id', function (req, res) {
  console.log('Request Id:', req.params.id); // 'anything'
});

read more about params type https://swagger.io/docs/specification/describing-parameters/

Mina Fawzy
  • 20,852
  • 17
  • 133
  • 156