带有获取参数的 Node.js/Express 路由
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8506658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js/Express routing with get params
提问by Erik
Let's say I have get route like this:
假设我有这样的路线:
app.get('/documents/format/type', function (req, res) {
var format = req.params.format,
type = req.params.type;
});
So if I make request like
所以如果我提出请求
http://localhost:3000/documents/json/mini
in my format and type variables will be 'json' and 'mini' respectively, but if I make request like
在我的格式和类型变量中将分别是 'json' 和 'mini',但是如果我提出这样的请求
http://localhost:3000/documents/mini/json
not. So my question is: how can I get the same variables in different order?
不是。所以我的问题是:如何以不同的顺序获得相同的变量?
回答by alessioalex
Your route isn't ok, it should be like this (with ':')
你的路线不行,应该是这样的(带':')
app.get('/documents/:format/:type', function (req, res) {
var format = req.params.format,
type = req.params.type;
});
Also you cannot interchange parameter order unfortunately.
For more information on req.params(and req.query) check out the api reference here.
不幸的是,您也无法交换参数顺序。有关req.params(和req.query)的更多信息,请查看此处的 api 参考。
回答by SCBuergel.eth
For Query parameters like domain.com/test?format=json&type=miniformat, then you can easily receive it via - req.query.
对于像domain.com/test?format=json&type=mini格式这样的查询参数,那么您可以通过 - req.query 轻松接收它。
app.get('/test', function(req, res){
var format = req.query.format,
type = req.query.type;
});

