首页 > 解决方案 > 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?

标签: javascriptnode.jsjsonexpressroutes

解决方案


所以你使用的是 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');
});

推荐阅读