19

I am using express JS and I have a set of routes that I have defined as follows

require('./moduleA/routes')(app);
require('./moduleB/routes')(app);

and so on. If I try to access any of the routes that I have not defined in the above routes, say

http://localhost:3001/test

it says

Cannot GET /test/

But instead of this I want to redirect to my app's index page. I want this redirection to happen to all of the undefined routes. How can I achieve this?

3 Answers 3

39

Try to add the following route as the last route:

app.use(function(req, res) {
    res.redirect('/');
});

Edit:

After a little researching I concluded that it's better to use app.get instead of app.use:

app.get('*', function(req, res) {
    res.redirect('/');
});

because app.use handles all HTTP methods (GET, POST, etc.), and you probably don't want to make undefined POST requests redirect to index page.

Sign up to request clarification or add additional context in comments.

1 Comment

@Srivathsa you're welcome) Sorry for my rash answer, it's better to use app.get. Take a look at my edited answer.
3

JUst try to put one get handler with * after all your get handlers like bellow.

app.get('/', routes.getHomePage);//When `/` get the home page

app.get('/login',routes.getLoginPage); //When `/login` get the login page

app.get('*',routes.getHomePage); // when  any other of these both then also homepage.

But make sure * should be after all, otherwise those will not work which are after * handler.

1 Comment

Just for your information: this solution leads to duplicate content, because there would be several pages with the same content, and this is bad for SEO. It's better to use HTTP redirection instead.
0

HTML file would be :

<form class="" action="/fail" method="post">
        <button type="submit" name="button">Redirect to Homepage!</button>
</form>

Your Node.js code would be:

app.post("/fail", (req, res)=>{  
  res.redirect("/"); 
});

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.