Search code examples
node.jsexpressparametersinfinite

How can I get a path as a key in express?


My current route lookup is app.get('/s/:key', ..., but there is a good reason to be able to get other keys passed in that same way. It is possible that I'll require getting paths that way as well--so basically I want to capture app.get('/s/:key/more/stuff/here/', ... and be able to read key independently of the /more/stuff/here portion. I don't have an issue with capturing the other parameters as an array of arguments and then concatenating them, but I don't know how to do that--I get 404s if I try to capture anything other than /s/:key with nothing following.

Is there a way to do this?


Solution

  • String routes in expressjs is like a regular expression so with that being said, you can use asterisk * as a wildcard:

    app.get('/s/:key/*', function(req, res, next) {
        var key = req.params.key;
        var someOtherParams = req.params[0];
    });
    

    Which will be:

    Then from there you can parse your wildcard. Like split it by /.


    OR if you want to be strict that it should not have other characters than alphanumeric, slashes and dashes, use regex directly on your route. Because on expressjs, you can't do a string route containing a single param with slashes then use regex on it and capture that param. It's a bit odd but you can look at this answer for the explanation.

    Anyway, for the code to do a regex on your 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 is capturing 2 groups (req.params[0]-->([A-Za-z0-9]+) and req.params[1]-->(([A-Za-z\-\/]+)*$)).

    The first group is actually your key, and the second group is the param that can contain alpha-numeric, dash and slash. Which you can parse or split by slashes. This way, your route is strict enough to not contain any other characters.

    Result will be: