我正在使用node.js 和express,我想在找不到请求的页面时显示自定义错误消息。目前我正在使用通配符来做到这一点。如果任何路由不匹配,则调用最后一个路由。 还有其他更好的方法吗?
My routes
app.get('/', routes.index);
app.get('/users', user.list);
app.get('/hello', hello.hello);
app.get('/*', error.error);
最佳答案
你所做的事情很好。我唯一要改变的是像这样的路线顺序
app.get('/users', user.list);
app.get('/hello', hello.hello);
app.get('/', routes.index);
app.get('/*', error.error);
要遵循的一个好规则是首先定义所有最不通用的路线。正如您可能知道的那样,这基本上告诉 Express 如果没有找到其他路线,则会显示错误消息,而通配符是一个很好的方法。
关于node.js 与express - 显示自定义错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17132494/