0
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 /?

0

1 Answer 1

1

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");
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.