首页 > 解决方案 > 使用 app.use((err, req, res, next)=>{}) 和 app.use("*", (err,req,res,next)=>{}) 表达 404 错误处理程序不返回集合404返回

问题描述

app.use("/login", login);

app.use("*", (err: any, req: Request, res: Response, next: NextFunction) => {
  console.log('errrorrrr')
  res.send('ERRORRRRR4040404040404 ******')
});

app.use((err: any, req: Request, res: Response, next: NextFunction) => {
  console.log('errrorrrr')
  res.send('ERRORRRRR4040404040404')
});

app.listen(config.port, () => {
  console.log(`Running at port ${config.port}`);
});

我在路由之后设置了这两个错误处理程序。我没有设置res.send(),而是Cannot GET /whynowork在我的节点上没有 console.log 的浏览器上。

如何正确设置404 Error?我试过只放一个,但它仍然返回Cannot GET /whynowork并且不通过错误处理程序。

标签: node.jsexpress

解决方案


将此路由器放在您编写的最后一个路由器之后,并且在第一个错误处理中间件之前(期望err作为第一个参数)

app.all('*', (req: Request, res: Response, next: NextFunction) => {
  res.status(404).json({
    message: 'hi its 404'
  })
})

在你上面写的情况下,这段代码应该在login路由器和ERRORERROR...404 ******路由器之间

app.use("/login", login);

app.all('*', (req: Request, res: Response, next: NextFunction) => {
  res.status(404).json({
    message: 'hi its 404'
  })
})

app.use("*", (err: any, req: Request, res: Response, next: NextFunction) => {
  console.log('errrorrrr')
  res.send('ERRORRRRR4040404040404 ******')
});

app.use((err: any, req: Request, res: Response, next: NextFunction) => {
  console.log('errrorrrr')
  res.send('ERRORRRRR4040404040404')
});

app.listen(config.port, () => {
  console.log(`Running at port ${config.port}`);
});

推荐阅读