Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express JS redirect to default page instead of "Cannot GET"

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?

like image 408
Srivathsa Avatar asked Aug 09 '14 08:08

Srivathsa


People also ask

How does Express handle 404 error?

In Express, 404 responses are not the result of an error, so the error-handler middleware will not capture them. This behavior is because a 404 response simply indicates the absence of additional work to do; in other words, Express has executed all middleware functions and routes, and found that none of them responded.

How do I redirect a page in Express?

The res. redirect() function lets you redirect the user to a different URL by sending an HTTP response with status 302. The HTTP client (browser, Axios, etc.) will then "follow" the redirect and send an HTTP request to the new URL as shown below.

Which method enables to redirect a route in Express?

In express, we can use the res. redirect() method to redirect a user to the different route. The res. redirect() method takes the path as an argument and redirects the user to that specified path.


1 Answers

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.

like image 154
Oleg Avatar answered Oct 21 '22 09:10

Oleg