1

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!

dfelix
  • 23
  • 1
  • 8

2 Answers2

1

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"}                           
Oluwafemi Sule
  • 36,144
  • 1
  • 56
  • 81
0

You can use the * sign after your desired route, something like this:

app.get('/*', (req, res) => {
    res.send(req.params[0]); 
});

// GET /:param1/:param2/...
Artemixx
  • 97
  • 5
  • Thanks! That works. But is there a way to assign a parameter name for the wildcard? – dfelix Jul 21 '22 at 15:43
  • You could mention any parameter before the ```*``` sign, something like ```/:param1/:param2/*```. Anything after these parameters will be considered a whole path string. – Artemixx Jul 21 '22 at 15:50