我正在尝试通过检查 cookie 为我的应用程序创建身份验证机制。所以我添加了 router.all('*')
来匹配每个请求,检查 cookie,然后转到实际的处理程序。但我需要它只匹配在“/”之后有一个或多个字符的请求。 (我想匹配/manage
、/m
或/about
,但不是/
)。
//Assuming a request for '/', this gets called first
router.all('*', function (request, response, next) {
//Stuff happening
next();
});
//This gets called on next(), which I do not want
router.get('/', function (request, response) {
//Stuff happening
});
//However this I do want to be matched when requested and therefore called after router.all()
router.post('/about', function (request, response) {
//Stuff happening
});
根据答案here您可以使用正则表达式进行路径匹配,但我真的不明白 '*'
是什么。它可能匹配所有内容,但对我来说它看起来不像正则表达式。
- 为什么
'*'
匹配/
? - 我需要向
all()
提供什么参数来匹配/about
而不是/
?
最佳答案
简单地说*
最后的。路由器按定义顺序检查。
所以:
router.get('/' ...
然后
router.all('*' ...
请记住 /
对 *
仍然有效, 所以 next()
来自 /
的电话将触发捕获所有进程。
关于javascript - 匹配 Express 中除 '/' 之外的所有路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37373740/