我正在使用express来重定向我的Web请求.我的一个Web请求包含三个可选参数,所以我有
router.get('/function/:param1?/:param2?/:param3?', function(req, res) {...});
Run Code Online (Sandbox Code Playgroud)
我的问题是,因为所有这三个参数都是可选的而不是相互依赖.例如,用户只能提供param3.在当前实现中,由于路由器格式中嵌入的序列,param3将被分配给param1变量.
如何实现如下所示的内容?
router.get('/function?param1=$1¶m2=$2¶m3=$3', function(req, res){...});
Run Code Online (Sandbox Code Playgroud)
你必须使用req.query.
如明文档中所述,req.query是一个包含已解析查询字符串的对象,默认为{}.
// GET /search?q=tobi+ferret
req.query.q
// => "tobi ferret"
// GET /shoes?order=desc&shoe[color]=blue&shoe[type]=converse
req.query.order
// => "desc"
req.query.shoe.color
// => "blue"
req.query.shoe.type
// => "converse"
Run Code Online (Sandbox Code Playgroud)
您不应该将查询参数放在路由中.你可以像你的路线一样
router.get('/function',function(req,res) {
console.log(req.query);
/*this will contain all the query string parameters as key/value in the object.
If you dint provide any in the URL, then it will be {}. */
/* So a simple way to check if the url contains
order as a query paramter will be like */
if(typeof req.query.order != "undefined") {
console.log(req.query.order);
} else {
console.log("parameter absent");
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2250 次 |
| 最近记录: |