1

I need to understand what this line of code means

app.get("/users/:id", function(req, res){
         var data = userModel.find().where('username', req);
         res.send(data);
     });

The part that I don't understand is "/users/:id", specifically the :id part. What does this syntax of http request mean?

femtoRgon
  • 32,893
  • 7
  • 60
  • 87
Cesar Jr Rodriguez
  • 1,691
  • 4
  • 22
  • 35
  • 1
    Related: http://stackoverflow.com/questions/20089582/how-to-get-url-parameter-in-express-node-js – Dan Dec 23 '15 at 21:05
  • This isn't so much a Node.js thing, as it is an Express thing (which is a Node framework). ":id" denotes a variable-path. You can retrieve the value of "id" from request, but I don't know Express very well, so wait for someone else to come along. – ndugger Dec 23 '15 at 21:06
  • Per [RFC3986](http://tools.ietf.org/html/rfc3986#section-3.3), a `:` is a normal, legal character in a path component in an URL other than the first component. So it should do nothing special in the client. In the server, it can do anything at all, just like any other path component. – David Schwartz Dec 23 '15 at 21:10

2 Answers2

1
Express uses the : to denote a variable in a route.
For example /user/42 will render a request for user id - 42
            /user/7  will render a request for user id - 7
but can be represented as a consistent form /users/:id
where id is the variable, : represents that whatever is after it is a 
variable, like here we have :id - id being the variable.

for reference check this out: http://expressjs.com/en/api.html
SBhalla
  • 31
  • 4
1

In the code you have above, sending a GET request to /users/42 will result in 42 being stored at req.params.id.

Essentially, :id tells express that whatever is in the request URI where :id is in the route declaration should be interpreted stored on the req.params object with a property name of id.

You would most likely want something more similar to this:

app.get("/users/:id", function(req, res){
    var data = userModel.find().where('id', req.params.id);
    res.send(data);
});
dvlsg
  • 5,378
  • 2
  • 29
  • 34