Home > Net >  nodejs: how can I only set redirect to basic url on expressjs?
nodejs: how can I only set redirect to basic url on expressjs?

Time:11-10

app.use("/", (req, res) => {
  res.redirect("https://www.google.com");
});

app.use("/app/v1", app);

I have this code and trying to redirect only on localhost:9999/. However, when I do localhost:9999/app/v1, I still get redirected by the app. Is there anyway that I can set the express to redirect only when the incoming url is just /?

CodePudding user response:

app.use mounts a middleware for the specified path.

The express application performs the middleware for the root path and other paths under the root path.

/
/app/v1
/any-other-path

Using regular expressions, you can ensure that the middleware is performed only for the root path like so:

app.use("/$", (req, res) => {
  res.redirect("https://www.google.com");
});

Another way is to configure a route handler instead of a middleware using app.get or other relevant request methods.

app.get("/", (req, res) => {
  res.redirect("https://www.google.com");
});
  • Related