Express JS redirects to the default page instead of "Can GET"

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

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

etc. 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, I want to redirect to the application index page. I want this redirection to happen with all undefined routes. How can I achieve this?

+6
source share
2 answers

Try adding the following route as the last route:

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

Edit:

After a little research, I came to the conclusion that it is 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 the undefined POST request redirected to the index page.

+15
source

JUst try to put one get handler with * after all your handlers, as shown below.

 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 that * must be in the end, otherwise they will not work, which are after the handler * .

+1
source

Source: https://habr.com/ru/post/973587/


All Articles