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);
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.
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.