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.
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.
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.
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.
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.
This is an express middleware.
In this case, yes, it will route /todos/anything
, and then req.params.id
will be set to 'anything'
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(); });
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