Search code examples
node.jsexpresskraken.js

Parenthesis around route path


I found this piece of code in a project using kraken and express

module.exports = function (router) {
    router.get('(/)', .....);
    router.get('(/nfc/read)', .....);
}

and I don't get why there are parenthesis around the routes paths.

Does it change something ? I can't find anything about it on the documentation of express and kraken. In the rest of the whole project all the other routes are normal, without parenthesis.


Solution

  • The difference between using and not using the parentheses is that when you use them then you will get the paths in req.params.

    For example in this example:

    let app = require('express')();
    app.get('/abc', (req, res) => {
        console.log(req.params[0]);
    });
    app.listen(3333, () => console.log('http://localhost:3333/'));
    

    what will be printed is undefined. But in this example:

    let app = require('express')();
    app.get('(/abc)', (req, res) => {
        console.log(req.params[0]);
    });
    app.listen(3333, () => console.log('http://localhost:3333/'));
    

    what will be printed is /abc.

    If there are more parentheses, there will be more elements in req.params. For example here:

    let app = require('express')();
    app.get('(/a)(bc)', (req, res) => {
        console.log(req.params[0]);
        console.log(req.params[1]);
    });
    app.listen(3333, () => console.log('http://localhost:3333/'));
    

    the same /abc route would be matched but what would be printed is:

    /a
    bc
    

    That is because the route is parsed as a regex and parentheses are capturing groups. See:

    Note that req.params is actually an object, not an array. This would return false:

    console.log(Array.isArray(req.params));
    

    It is just an object that happens to have numbers (actually strings like "0" and "1") as its keys.