简体   繁体   中英

Express.js match only exactly '/' route

So I'm serving a web page on the root route '/', and this page had an authentication middleware. 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. Use app.get instead.

When using app.use("/") this will match any path and method that starts with "/" , This happens because app.use() is intended for global middlewares.

Instead you can use app.get("/", yourTargetedMiddlewaer) to target a specific route and a specific method (GET) in this case.

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:

http://localhost:3000/ or 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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