node.js - How can I get a path as a key in express? -
my current route lookup app.get('/s/:key', ..., there reason able other keys passed in same way. possible i'll require getting paths way well--so want capture app.get('/s/:key/more/stuff/here/', ... , able read key independently of /more/stuff/here portion. don't have issue capturing other parameters array of arguments , concatenating them, don't know how that--i 404s if try capture other /s/:key nothing following.
is there way this?
string routes in expressjs regular expression being said, can use asterisk * wildcard:
app.get('/s/:key/*', function(req, res, next) { var key = req.params.key; var someotherparams = req.params[0]; }); which be:
- http://example.com/s/1/some/other/stuff -
req.params.key=1,req.params[0]=some/other/stuff
then there can parse wildcard. split /.
or if want strict should not have other characters alphanumeric, slashes , dashes, use regex directly on route. because on expressjs, can't string route containing single param slashes use regex on , capture param. it's bit odd can @ answer explanation.
anyway, code regex on route:
app.get(/s\/([a-za-z0-9]+)\/(([a-za-z\-\/]+)*$)/, function(req, res, next) { var key = req.params[0]; var someotherparams = req.params[1]; }); which capturing 2 groups (req.params[0]-->([a-za-z0-9]+) , req.params[1]-->(([a-za-z\-\/]+)*$)).
the first group key, , second group param can contain alpha-numeric, dash , slash. can parse or split slashes. way, route strict enough not contain other characters.
result be:
- http://example.com/s/1/some/other/stuff -
req.params[0]=1,req.params[1]=some/other/stuff - http://example.com/s/1/some-other/stuff -
req.params[0]=1,req.params[1]=some-other/stuff - http://example.com/s/1/some/other-weird/stuff -
req.params[0]=1,req.params[1]=some/other-weird/stuff - http://example.com/s/1/some/other/stuff-one -
req.params[0]=1,req.params[1]=some/other/stuff-one - http://example.com/s/1/some&other/stuff - error 404,
¬ permitted in regex
Comments
Post a Comment