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?

3
  • 1
    Related: stackoverflow.com/questions/20089582/… Commented Dec 23, 2015 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. Commented Dec 23, 2015 at 21:06
  • Per RFC3986, 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. Commented Dec 23, 2015 at 21:10

2 Answers 2

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);
});
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.