繁体   English   中英

Express.js 仅完全匹配 '/' 路由

[英]Express.js match only exactly '/' route

所以我在根路由“/”上提供了一个 web 页面,这个页面有一个身份验证中间件。 使用常规

app.use('/', authorizeFront, express.static('../client/dist'));

会导致每条路线都经过身份验证,这是我试图避免的。 我也尝试过使用正则表达式来精确匹配“/”,但它似乎不起作用。

app.use('/^/$/', authorizeFront, express.static('../client/dist'));

有没有官方的方法可以做到这一点? 谢谢!

app.use 进行部分匹配。 请改用 app.get。

使用app.use("/")时,这将匹配任何以"/"开头的路径和方法,这是因为app.use()适用于全局中间件。

在这种情况下,您可以使用app.get("/", yourTargetedMiddlewaer)来定位特定路由和特定方法(GET)

另一种方法可以是:


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();
    }
});

这将命中所有请求的中间件,但您可以控制要调用身份验证器的请求。

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);

我测试了这个,只有当我像这样使用 URL 时,我的控制台才会打印:

http://localhost:3000/ 或 http://localhost:3000

还要注意我使用的中间件的顺序,基本根中间件应该设置在顶部。 您可以根据需要进行更多修改

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM