user6758349
user6758349

Reputation:

How to route dynamic URL in Express

Say I have the following URL:

/page?name=myname&age=25

Where name and age have dynamic values.

How do I construct a router get function for this page?

Option 1:

router.route("/page").get(function(req, res) {
    console.log("got page");
}

Option 2:

router.route("/page?name&age").get(function(req, res) {
    console.log("got page");
}

Upvotes: 1

Views: 4669

Answers (3)

warl0ck
warl0ck

Reputation: 3464

You can construct the route for the page as:

router.route("/page").get(function(req, res) {
    console.log("got page");
}

and as for the query parameters you can access them as:

req.query.YOUR_QUERY_NAME

therefore in your case it will become req.query.name and req.query.age which will return the values "myname" and 25 respectively.

you can read more on Documentation page

In case you are also having or planning to have routes like: http://localhost:3000/name/user/age/84

In that case you can have you routes config as:

router.route("/name/:myName/age/:myage").get(function(req, res) {
name = req.params.myName;
age = req.params.myage;
});

as req.params returns the object with value params here req.params if console.log will return {"myName":"user", "myage":"84"} object

you can read more about route params from Route params link

Upvotes: 1

Anne Douwe
Anne Douwe

Reputation: 691

You can use req.query.name and req.query.age for that, you don't need a specific route, just router.route("/page")...

You can also use: Route parameters to get a clean URL

Upvotes: 0

Kumar Nitesh
Kumar Nitesh

Reputation: 1652

It will be

router.route("/page").get(function(req, res) {
    console.log("got page");
}

?name=myname&age=25 => are req parameters. which can be accessed by

req.query.name
req.query.age

Upvotes: 3

Related Questions