38

I have an application which serves file listings.

The application must respond to following routes:

/company/:id
/company/:id/dir
/company/:id/dir/dir

Here /company/:id is a route with no path specified e.g a root directory. I was thinking for something like app.get('/company/:id/:path', ... which obviously doesn't work.

How can I define a route which responds to all of the examples?

Gerstmann
  • 5,368
  • 6
  • 37
  • 57

1 Answers1

84

Use /company/:id* (note trailing asterisk).

Full example

var express = require('express')();

express.use(express.router);

express.get('/company/:id*', function(req, res, next) {
    res.json({
        id: req.params['id'],
        path: req.params[0]
    });    
});

express.listen(8080);
Linus Unnebäck
  • 23,234
  • 15
  • 74
  • 89
Prinzhorn
  • 22,120
  • 7
  • 61
  • 65
  • 5
    Or `/company/:id*` (without the slash). – robertklep May 30 '13 at 08:06
  • @robertklep perfect, that handles all cases – Prinzhorn May 30 '13 at 08:14
  • 1
    The route parameters is { '0': 'adfadf/fasdfa', slug: 'aaaa' } when I request /aaaa/adfadf/fasdfa . i don't know where the key '0' come from – Như Là Mơ Jan 11 '19 at 08:51
  • 4
    @NhưLàMơ `:id*` turns params into an array. So the :slug part is given the "slug" named property (assuming your path is `/:slug*`) in the params object, and then the 0th index is the rest of the matched part of the path. – Redmega Jul 15 '19 at 22:21