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.
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"); });
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.
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.
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).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With