【问题标题】:how to use a slash in route parameters如何在路由参数中使用斜线
【发布时间】:2015-12-01 13:57:46
【问题描述】:

我有一个 GET REST 服务,它需要接受带有 / 的参数

URL = "/term/:term/amount/:amount" 其中 :term 可以是类似“para/5MG”的字符串。

有没有办法在快递中做到这一点?随着我的 api 被使用,我不想用 queryparams 重写它。

【问题讨论】:

标签: javascript node.js rest url express


【解决方案1】:

本机,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

【讨论】:

  • 谢谢,URI 编码似乎是最好的方法。
【解决方案2】:
app.get('/term/:term/amount/:amount',  function(req, res) {
    // your code here
})

【讨论】:

  • 对我不起作用,你试过curl <hostname>/term/para/5MG/amount/5 吗?
  • 你需要对正斜杠进行 URI 编码,试试这个:curl <hostname>/term/para%2F5MG/amount/5
  • 那为什么不是你的答案的一部分呢?
  • 最初阅读问题时,我没有注意到正斜杠作为参数一部分的细微差别。我以为 OP 只是不知道如何使用命名参数创建快速路由。
猜你喜欢
  • 2013-06-29
  • 2016-12-31
  • 1970-01-01
  • 2013-07-12
  • 1970-01-01
  • 2014-09-15
  • 1970-01-01
  • 2017-01-05
  • 2020-05-29
相关资源
最近更新 更多