Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 749
glog Avatar asked Dec 04 '15 18:12

glog


People also ask

What is Express router ()?

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.

What is req params ID?

The req. params property is an object containing properties mapped to the named route “parameters”. For example, if you have the route /student/:id, then the “id” property is available as req.params.id. This object defaults to {}. Syntax: req.params.

How does routing work in Express?

A route method is derived from one of the HTTP methods, and is attached to an instance of the express class. The following code is an example of routes that are defined for the GET and the POST methods to the root of the app. Express supports methods that correspond to all HTTP request methods: get , post , and so on.

How do I declare a router in node JS?

Routing with Express in Node: Express. js has an “app” object corresponding to HTTP. We define the routes by using the methods of this “app” object. This app object specifies a callback function, which is called when a request is received.


2 Answers

This is an express middleware.

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

like image 171
Rilke Petrosky Avatar answered Oct 04 '22 09:10

Rilke Petrosky


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(); }); 
like image 38
Bilash Avatar answered Oct 04 '22 10:10

Bilash