node.jsexpressexpress-router

Path as parameter in route path


I need to follow a spec that requires a GET using a "path" in route path.

Scenario #1: https://example.com/param1/param2/file.txt

Scenario #2: https://example.com/param1/param2/folder/file.txt

Initially I tried with the very standard implementation:

app.get('/:param1/:param2/:path', (req, res) => {
  res.send(req.params)
})

It works as expected for first scenario. However for second one I receive a 404 as express router looks for the complete path, that of course.. does not exist.

I know, passing the path as url parameter would easily solve this problem. But requirements are to use the path... as path.

How can I trick express router to get the rest of the path as my last parameter?

Thank you!


Solution

  • You can provide a regex pattern to match the remaining part of the route.

    const express = require('express');
    
    app = express();
    
    app.get('/:param1/:param2/:path([\\w\\W]+)', (req, res) => {
        res.send(req.params)
      })
      
      
    app.listen(9000);
    
    curl -X GET http://localhost:9000/foo/bar/bat
    {"param1":"foo","param2":"bar","path":"bat"}
    
    curl -X GET http://localhost:9000/foo/bar/bat/def.dex
    
    {"param1":"foo","param2":"bar","path":"bat/def.dex"}