Express JSredirect到默认页面而不是“无法获取”
我使用快递JS,我有一套我已经定义如下的路线
require('./moduleA/routes')(app); require('./moduleB/routes')(app);
等等。 如果我尝试访问我没有在上面的路线中定义的任何路线,说
http://localhost:3001/test
它说
Cannot GET /test/
但是,而不是我想redirect到我的应用程序的索引页面。 我想这个redirect发生在所有未定义的路由上。 我怎样才能做到这一点?
尝试添加以下路线作为最后的路线:
app.use(function(req, res) { res.redirect('/'); });
编辑:
经过一番研究,我得出结论:使用app.get
代替app.use
:
app.get('*', function(req, res) { res.redirect('/'); });
因为app.use
处理所有的HTTP方法( GET
, POST
等),你可能不想让未定义的POST
请求redirect到索引页面。
在所有得到像波纹pipe之类的处理程序之后,尽量把一个get
处理程序放在*
之上。
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.
但是要确保*
应该是最终的,否则那些在*
handler之后将不起作用。