glog
glog

Reputation: 829

Express router - :id?

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.

Upvotes: 47

Views: 77658

Answers (6)

Mina Fawzy
Mina Fawzy

Reputation: 21472

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/

Upvotes: 0

Sven Cazier
Sven Cazier

Reputation: 407

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).

Upvotes: 1

Md Nazmul Hossain
Md Nazmul Hossain

Reputation: 2943

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();
});

Upvotes: 25

Roshan
Roshan

Reputation: 641

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();
});

Upvotes: 4

Rilke Petrosky
Rilke Petrosky

Reputation: 1185

This is an express middleware.

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

Upvotes: 49

Nir Levy
Nir Levy

Reputation: 12953

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

Upvotes: 2

Related Questions