【发布时间】:2015-12-01 13:57:46
【问题描述】:
我有一个 GET REST 服务,它需要接受带有 / 的参数
URL = "/term/:term/amount/:amount" 其中 :term 可以是类似“para/5MG”的字符串。
有没有办法在快递中做到这一点?随着我的 api 被使用,我不想用 queryparams 重写它。
【问题讨论】:
标签: javascript node.js rest url express
我有一个 GET REST 服务,它需要接受带有 / 的参数
URL = "/term/:term/amount/:amount" 其中 :term 可以是类似“para/5MG”的字符串。
有没有办法在快递中做到这一点?随着我的 api 被使用,我不想用 queryparams 重写它。
【问题讨论】:
标签: javascript node.js rest url express
本机,express 尝试在/ 拆分,因此您必须手动拆分。这是这样做的一个例子:
app.get('/term/\\S+/amount/:amount', function (req, res, next){
var match;
if(match = req.path.match(/^\/term\/(.*?)\/amount\/(.*)$/)){
var term = match[1];
var amount = req.params.amount;
// or do whatever you like
res.json({term: term, amount: amount})
}else{
res.sendStatus(404);
}
})
用这种方法你会失去很多 expresse 的内置魔法。首先对参数进行 URI 编码可能会更好。 (像这样:term/para%2F5MG/amount/3)
【讨论】:
app.get('/term/:term/amount/:amount', function(req, res) {
// your code here
})
【讨论】:
curl <hostname>/term/para/5MG/amount/5 吗?
curl <hostname>/term/para%2F5MG/amount/5