【问题标题】:Express 404 error handers with app.use((err, req, res, next)=>{}) and app.use("*", (err,req,res,next)=>{}) do not return set 404 return使用 app.use((err, req, res, next)=>{}) 和 app.use("*", (err,req,res,next)=>{}) 表达 404 错误处理程序不返回集合404返回
【发布时间】:2021-11-01 22:22:11
【问题描述】:
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.js express


    【解决方案1】:

    将此路由器放在您编写的最后一个路由器之后,并且在第一个错误处理中间件之前(期望 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}`);
    });
    

    【讨论】:

      猜你喜欢
      • 2015-04-29
      • 1970-01-01
      • 2020-01-14
      • 1970-01-01
      • 2019-10-27
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      • 2022-12-11
      相关资源
      最近更新 更多