[Fixed] Express JS redirect to default page instead of "Cannot GET"

Issue

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?

Solution

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.

Leave a Reply

(*) Required, Your email will not be published