Express JS重定向到默认页面,而不是"Cannot GET". [英] Express JS redirect to default page instead of "Cannot GET"

查看:358
本文介绍了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方法(GETPOST等),并且您可能不想使未定义的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.

这篇关于Express JS重定向到默认页面,而不是"Cannot GET".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆