简体   繁体   中英

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");
}

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM