Express JS重定向到默认页面,而不是"Cannot GET".
我使用的是Express JS,我有一组定义如下的路由
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
说
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?
尝试将以下路由添加为最后一条路由:
Try to add the following route as the last route:
app.use(function(req, res) {
res.redirect('/');
});
经过一番研究,我得出结论,最好使用app.get
代替app.use
:
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('/');
});
因为app.use
处理所有HTTP方法(GET
,POST
等),并且您可能不想使未定义的POST
请求重定向到索引页.
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.