Express-js wildcard routing to cover everything under and including a path

node.jsExpress

node.js Problem Overview


I'm trying to have one route cover everything under /foo including /foo itself. I've tried using /foo* which work for everything except it doesn't match /foo. Observe:

var express = require("express"),
    app = express.createServer();
    
app.get("/foo*", function(req, res, next){
  res.write("Foo*\n");
  next();
});

app.get("/foo", function(req, res){
  res.end("Foo\n");
});

app.get("/foo/bar", function(req, res){
  res.end("Foo Bar\n");
});

app.listen(3000);

Outputs:

$ curl localhost:3000/foo
Foo
$ curl localhost:3000/foo/bar
Foo*
Foo Bar

What are my options? The best I've come up with is to route /fo* which of course isn't very optimal as it would match way too much.

node.js Solutions


Solution 1 - node.js

I think you will have to have 2 routes. If you look at line 331 of the connect router the * in a path is replaced with .+ so will match 1 or more characters.

https://github.com/senchalabs/connect/blob/master/lib/middleware/router.js

If you have 2 routes that perform the same action you can do the following to keep it DRY.

var express = require("express"),
    app = express.createServer();

function fooRoute(req, res, next) {
  res.end("Foo Route\n");
}

app.get("/foo*", fooRoute);
app.get("/foo", fooRoute);

app.listen(3000);

Solution 2 - node.js

The connect router has now been removed (https://github.com/senchalabs/connect/issues/262), the author stating that you should use a framework on top of connect (like Express) for routing.

Express currently treats app.get("/foo*") as app.get(/\/foo(.*)/), removing the need for two separate routes. This is in contrast to the previous answer (referring to the now removed connect router) which stated that "* in a path is replaced with .+".

Update: Express now uses the "path-to-regexp" module (since Express 4.0.0) which maintains the same behavior in the version currently referenced. It's unclear to me whether the latest version of that module keeps the behavior, but for now this answer stands.

Solution 3 - node.js

> It is not necessary to have two routes. > > Simply add (/*)? at the end of your path string. > > For example, app.get('/hello/world(/*)?' /* ... */)

Here is a fully working example, feel free to copy and paste this into a .js file to run with node, and play with it in a browser (or curl):

const app = require('express')()

// will be able to match all of the following
const test1 = 'http://localhost:3000/hello/world'
const test2 = 'http://localhost:3000/hello/world/'
const test3 = 'http://localhost:3000/hello/world/with/more/stuff'

// but fail at this one
const failTest = 'http://localhost:3000/foo/world'

app.get('/hello/world(/*)?', (req, res) => res.send(`
    This will match at example endpoints: <br><br>
    <pre><a href="${test1}">${test1}</a></pre>
    <pre><a href="${test2}">${test2}</a></pre>
    <pre><a href="${test3}">${test3}</a></pre>

    <br><br> Will NOT match at: <pre><a href="${failTest}">${failTest}</a></pre>
`))

app.listen(3000, () => console.log('Check this out in a browser at http://localhost:3000/hello/world!'))

Solution 4 - node.js

In array you also can use variables passing to req.params:

app.get(["/:foo", "/:foo/:bar"], /* function */);

Solution 5 - node.js

For those who are learning node/express (just like me): do not use wildcard routing if possible!

I also wanted to implement the routing for GET /users/:id/whatever using wildcard routing. This is how I got here.

More info: https://blog.praveen.science/wildcard-routing-is-an-anti-pattern/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKit SundeView Question on Stackoverflow
Solution 1 - node.jsserbyView Answer on Stackoverflow
Solution 2 - node.jsJohannView Answer on Stackoverflow
Solution 3 - node.jsSomo S.View Answer on Stackoverflow
Solution 4 - node.jsDrDimedrolView Answer on Stackoverflow
Solution 5 - node.jsthrobiView Answer on Stackoverflow