Express JS redirect to default page instead of “Cannot GET”

后端 未结 2 2012
醉酒成梦
醉酒成梦 2021-02-19 16:52

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


        
2条回答
  •  名媛妹妹
    2021-02-19 17:43

    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.

提交回复
热议问题