nbro
nbro

Reputation: 15847

What's the purpose of using ":" before a name in the path of a URL?

This might seem a trivial problem, but I have searched for a while for a concrete authoritative answer, but nothing came out so far.

I have been using express.js, and I have been seeing URLs' handlers with paths such as

app.get("/users/:id", function(req, res) {
    res.send(req.params)
})

or

app.get("/users/:name/photos", function(req, res) {
    res.send(req.params)
})

But I am not completely sure of the purpose of using : before id (or name) in those cases.

I know that, if I use : before id, id will be available as parameter of req.params, i.e. req.params.id. Usually id is an integer, but this is actually not strictly necessary, it could be anything else (e.g. string).

My guess about the reason of using : before a name in the path of a URL is simply to say to express that instead of :id or :name, we can pass whatever we want of any type. :id or :name are considered variables. Is this guess correct?

What are the purposes of using : when handling routing? When should we use it?

Upvotes: 0

Views: 138

Answers (2)

Moin
Moin

Reputation: 1143

You are right.

: is just used to set a route. It could have been a ! or @ or anything else for that matter. It declares a variable in route.

In your code:

app.get("/users/:id", function(req, res) {
    res.send(req.params)
})

/users/:id becomes a route. It means anything after users/ will be caught by this handler and become available in the id variable inside it. It doesn't have to be an integer.

Here:

app.get("/users/:name/photos", function(req, res) {
    res.send(req.params)
})

The route is defined something like this: /users/john/photos/

In this case, john is a variable which matched the route set.

Upvotes: 0

mscdex
mscdex

Reputation: 106696

The : just indicates a named variable as a placeholder in that part of the url. Without it, id would get matched literally in the url and would not be interpreted as a dynamic placeholder. That's all there is to it.

Upvotes: 5

Related Questions