node.js - 使用 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
并且不通过错误处理程序。
解决方案
将此路由器放在您编写的最后一个路由器之后,并且在第一个错误处理中间件之前(期望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}`);
});
推荐阅读
- java - Handlebars java - quotes in helper
- wso2 - Wso2 MicroIntegrator Prometheus 指标 -DenablePrometheusApi
- docker - 如何将 docker 图像标签添加到流利的日志中
- azure-active-directory - 如何取消用户对 Web 应用程序的同意
- javascript - 无法将 PHP 变量转换为 javascript 函数
- spring-boot - Spring Boot,无法使用我的 UserDetailsService
- terraform - gitignore .tfvars 但不是 .auto.tfvars
- selenium - Browserstack 上的 Safari 现在可以正常工作
- javascript - 带有 firebase nuxt 模块的 Firebase 存储在删除文件后无法读取未定义的属性“删除”
- unit-testing - 使用接口进行模拟以进行测试