2

我正在使用 node.js 和 express,我想在找不到请求的页面时显示自定义错误消息。目前我正在使用通配符来做到这一点。如果任何路由不匹配,则调用最后一个路由。有没有其他更好的方法来做到这一点?

我的路线

app.get('/', routes.index);
app.get('/users', user.list);
app.get('/hello', hello.hello);
app.get('/*', error.error);
4

1 回答 1

3

你在做什么是好的。我唯一要改变的就是这样的路线顺序

 app.get('/users', user.list);
 app.get('/hello', hello.hello);
 app.get('/', routes.index);
 app.get('/*', error.error);

一个好的规则是首先定义所有最不通用的路线。正如您可能知道的那样,这基本上告诉 express,如果没有找到其他路线,则显示错误消息,通配符是一种很好的方法。

于 2013-06-16T11:16:16.550 回答