javascript - How to handle invalid routes from two files
问题描述
I am trying to resolve a scenario where I want to catch invalid routes and throw a message in Node.
I have two files, one User file and one Task file. If I hit an endpoint/route that does not exist, I want to throw a message to the screen that says it is an invalid route.
My question is that I specifically added a piece of code that catches these invalid routes in both files, user.js and task.js, but when I search for a valid request in the second route (task.js) I am getting an invalid route error from the first file (user.js). This is the code that I have in both files at the end of each file:
//handles invalid route requests (in user.js file)
router.get('*', (req, res) => {
return res.status(404).send({error: 'Route not found'})
})
//handles invalid route requests (in task.js file)
router.all('*',(req, res) => {
return res.status(404).json({error: 'Route not found'})
})
Is the solution to have this piece of code in only one of the route files? For example, should this code only be present in the task.js file so that it can check both route files until it reaches the invalid route case?
解决方案
所以你使用的是 express-js ......我曾经用它在 seleton 中使用 express-skeleton 模块生成......
正如你在 github 页面中看到的,app.js 文件的架构是调用你所有的路由和错误路由之后。请看这里
在 app.js 的末尾:
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
推荐阅读
- google-chrome - VSCode 中的 Chrome 调试器不显示网页
- python - 无法在 MacOS 11.1 上使用 pyenv 安装带有共享库的 Python 构建
- sql - H2 不允许我批量插入数据
- mysql - SQL查询,获取所有没有给定状态值的id
- discord - 我正在尝试制作一个不和谐的机器人,让 DM 是随机用户,它要么只有我,要么我得到一个错误
- ruby-on-rails - Rails Devise,如何正确嵌套资源
- excel - Excel VBA 的局限性?
- python - 使用python,我如何找出一个字符串是否包含除另一个列表中的字符之外的任何字符
- r - R If then do - 如何根据条件创建变量
- arrays - 将 PowerShell 中的多值属性导出到 Excel - 尝试使用哈希表数组实现自动化