[英]Named arguments in routing in Express.js
I can't seem to find information about this anywhere. 我似乎在任何地方都找不到有关此信息。
I want to be able to do requests like this: url/list/message=hello?id=1234
我希望能够发出如下请求:
url/list/message=hello?id=1234
But like I've said, I haven't been able to find any information on how to do this in Express. 但是,就像我说过的那样,我无法在Express中找到有关如何执行此操作的任何信息。
My initial guess was to do this: 我最初的猜测是这样做:
app.put('/list/message=:msg?id=:id', function (req, res) { ... });
But this doesn't quite work. 但这并不完全有效。 Is there any way to do this at all in Express?
在Express中,有什么办法可以做到这一点?
What you're referring to is generally called a query string , and we have a powerful URL parsing library in node to handle that for us. 您所指的通常称为查询字符串 ,并且节点中具有功能强大的URL解析库来为我们处理。
Try this: 尝试这个:
require('url');
...
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
Then, you can use query.id
and get 1234
, IF you change your route to this: 然后,如果您将路由更改为此,则可以使用
query.id
并获取1234
:
app.put('/list/message=:msg', function (req, res) { ... });
Ideally, you should check that query.id
exists before attempting to read from it. 理想情况下,您应在尝试读取
query.id
之前检查其query.id
存在。 I would also recommend against using an message=:msg
. 我也建议不要使用
message=:msg
。 Instead, I would rewrite the whole thing as 相反,我会将整个内容重写为
app.put('/list/:id', function (req, res) {
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
if (query.message) {...}
});
which is a slightly different structure than you have currently, but is more in line with how a great deal of APIs handle their routing. 这种结构与您目前使用的结构略有不同,但与大量API处理其路由的方式更加一致。
You can't do it like that. 你不能那样做。 What you can do is:
您可以做的是:
app.put('/list/message/:msg', function (req, res) {
var msg = req.params.msg;
var url = require('url');
var id = url.parse(req.url, true).query.id;
});
Your URL will look like this: url/list/message/hello?id=1234 您的网址将如下所示:url / list / message / hello?id = 1234
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.