Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the Id from the URL while using node.js

Tags:

I am quite new to Javascript and node.js and I'm trying to create a REST API, and the urls will be of the form.

  1. /user/{userId}/docs

I am trying to get the value of {userId}, which in the case of /user/5/docs will be 5.

I could try to pass this as a request parameter(in the querystring or in the body, depending on the GET or POST method), but the url looks more intuitive when it is formed this will. Plus there are many more urls which are like these.

I am wondering if there are any node modules like express which provide for this.

I am a traditional Java user and Jersey framework used to provide such a thing in Java.

Thanks, Tuco

like image 556
Tuco Avatar asked Aug 28 '12 13:08

Tuco


People also ask

How do I find my user ID in Node JS?

To get the OS current user id or ( uid ) in Node. js, you can use the userInfo() method from the os module and then use the uid property from the object returned.

What is req params ID in Node JS?

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.


1 Answers

Spend some time with the documentation. Express uses the : to denote a variable in a route:

app.get('/user/:id/docs', function(req, res) {     var id = req.params.id; }); 
like image 59
josh3736 Avatar answered Oct 07 '22 19:10

josh3736