Express-js 通配符路由以覆盖路径下和包括路径下的所有内容 [英] Express-js wildcard routing to cover everything under and including a path

查看:30
本文介绍了Express-js 通配符路由以覆盖路径下和包括路径下的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让一条路线覆盖 /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*
");
  next();
});

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

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

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 too 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

如果您有 2 条路线执行相同的操作,您可以执行以下操作来保持它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
");
}

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

app.listen(3000);

这篇关于Express-js 通配符路由以覆盖路径下和包括路径下的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆