简体   繁体   中英

how to use a slash in route parameters

I have a GET REST service which needs to accept parameters with a /

URL = "/term/:term/amount/:amount" where :term can be a string like "para/5MG".

is there a way to do this in express? as my api gets used, I prefer not to rewrite it with queryparams.

Natively, express tries to split at / so you'll have to do splitting by hand. Here is one example of doing so:

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);
  }
})

You'll loose a lot of expresse's built in magic with this method. It probably would be better to URI-encode the parameter in the first place. (like this: term/para%2F5MG/amount/3 )

app.get('/term/:term/amount/:amount',  function(req, res) {
    // your code here
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM