Express-js通配符路由以覆盖并包含路径的所有内容 [英] Express-js wildcard routing to cover everything under and including a path
问题描述
我试图让一条路线覆盖 / foo
下的所有内容,包括 / foo
本身。我尝试使用 / foo *
,它适用于所有的,除了它不匹配 / foo
。观察:
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);
输出:
$ curl localhost:3000/foo
Foo
$ curl localhost:3000/foo/bar
Foo*
Foo Bar
我有什么选择?我想出的最好的方法是路由 / fo *
,这当然不是最佳的,因为它会匹配很多。
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 to much.
推荐答案
我想你必须有2条路线。如果您查看连接路由器的第331行,路径中的*将被替换为+,所以将匹配1个或更多个字符。
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
如果您有两条执行相同操作的路线,您可以执行以下操作来保持DRY。
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);
这篇关于Express-js通配符路由以覆盖并包含路径的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!