Home > other >  Express.js match only exactly '/' route
Express.js match only exactly '/' route

Time:02-22

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!

CodePudding user response:

app.use does a partial match. Use app.get instead.

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

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

  • Related