Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 208
Kit Sunde Avatar asked May 28 '11 12:05

Kit Sunde


People also ask

What is a wildcard route Express?

Express allow you to use a wildcard within a route path using * . For example, the path defined below can be access using anything that follows the base URL (for example, if you wanted to build a “catch all” that caught routes not previously defined). app. get('/*',function(req,res) { req. send("I am Foo"); });

What is routing and how routing works in Express js?

Routing refers to how an application's endpoints (URIs) respond to client requests. For an introduction to routing, see Basic routing. You define routing using methods of the Express app object that correspond to HTTP methods; for example, app. get() to handle GET requests and app.

What is the correct order of defining routing using Express methods are?

The order is first come first serve. In your case, if user hits /api, he will get response from api, but if you write /:name route before /api , /:name will serve for /api requests also.

What is var Express require (' Express ')?

var express = require('express'); => Requires the Express module just as you require other modules and and puts it in a variable. var app = express(); => Calls the express function "express()" and puts new Express application inside the app variable (to start a new Express application).


1 Answers

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); 
like image 140
serby Avatar answered Oct 19 '22 19:10

serby