[英]Express.js match only exactly '/' route
So I'm serving a web page on the root route '/', and this page had an authentication middleware.所以我在根路由“/”上提供了一个 web 页面,这个页面有一个身份验证中间件。 Using regular使用常规
app.use('/', authorizeFront, express.static('../client/dist'));
would cause every route to be authenticated, which is what I'm trying to avoid.会导致每条路线都经过身份验证,这是我试图避免的。 I've also tried using regex to match exactly '/' but it doesn't seem to be working.我也尝试过使用正则表达式来精确匹配“/”,但它似乎不起作用。
app.use('/^/$/', authorizeFront, express.static('../client/dist'));
Is there any official way to do this?有没有官方的方法可以做到这一点? Thanks!谢谢!
app.use does a partial match. app.use 进行部分匹配。 Use app.get instead.请改用 app.get。
When using app.use("/")
this will match any path and method that starts with "/"
, This happens because app.use()
is intended for global middlewares.使用app.use("/")
时,这将匹配任何以"/"
开头的路径和方法,这是因为app.use()
适用于全局中间件。
Instead you can use app.get("/", yourTargetedMiddlewaer)
to target a specific route and a specific method (GET)
in this case.在这种情况下,您可以使用app.get("/", yourTargetedMiddlewaer)
来定位特定路由和特定方法(GET)
。
Another way to do this could be:另一种方法可以是:
app.use("*", (req, res, next) => {
if (req.baseUrl === "") { // For / requests baseUrl will be empty
// Call authenticator and then call next() if auth succeeds else call next(err)
} else {
console.info("Bypassing Authentication");
next();
}
});
This will hit the middleware for all requests, but you have the control for which request you want to call the authenticator.这将命中所有请求的中间件,但您可以控制要调用身份验证器的请求。
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(req, res, next) {
if ( req.path === "/") {
console.log("request matches your special route pattern", req.url);
// return authorizeFront(); call your code
}
next();
});
app.use('/', indexRouter);
app.use('/users', usersRouter);
I tested this and my console prints only when i use URL like this:我测试了这个,只有当我像这样使用 URL 时,我的控制台才会打印:
http://localhost:3000/ or http://localhost:3000 http://localhost:3000/ 或 http://localhost:3000
Also notice the sequence of middleware I have used, base root middleware should be set at top.还要注意我使用的中间件的顺序,基本根中间件应该设置在顶部。 You can do more modification as per your needs您可以根据需要进行更多修改
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.