javascript - 如何在 express 上为 404 错误添加中间件
问题描述
环境
app.use("/api/tobaccos", tobaccos);
app.use(function(err, req, res, next) {
console.error(err.message);
});
接口:
router.get("/:id", async (req, res) => {
console.log("GET TOBACCO:" + req.params.id);
await Tobacco.findById(req.params.id)
.then(tobacco => res.status(200).json({ status: "success", data: tobacco }))
.catch(error => res.status(404).json({
status: "fail",
msg: "Tobacco not found!",
code: "error.tobaccoNotFound"
}));
});
我正在尝试为所有 404 错误添加中间件
app.use(function(err, req, res, next) {
console.error(err.message);
});
或者这不起作用
app.get('*', function(req, res){
res.status(404).send('what???');
});
怎么了?
解决方案
在 Express 中,404 响应不是错误的结果,因此错误处理程序中间件不会捕获它们。这种行为是因为 404 响应只是表明没有额外的工作要做;也就是说,Express 已经执行了所有的中间件函数和路由,发现没有一个响应。您需要做的就是在堆栈的最底部(在所有其他函数下方)添加一个中间件函数来处理 404 响应:
app.use(function (req, res, next) {
res.status(404).send("Sorry can't find that!")
})
在运行时在 express.Router() 的实例上动态添加路由,这样路由就不会被中间件函数取代。
推荐阅读
- swift - 从数据库加载数据并将其加载到 Vapor 3 中的视图的正确方法?
- ios - 通知 ios 上的自定义音频播放器控件
- bazel - Bazel-如何获取目标的所有传递源
- ios - 我如何将 NSRangeException 解决为 swift 4?
- python - 将scrapy项目导出到不同的文件
- opengl-es-2.0 - 开启深度测试,还是不行?
- ruby-on-rails - Rails 说没有路线匹配,但我在“rake 路线”中看到它
- reactjs - 组件不会重新渲染
- string - 将字符串的索引与字符进行比较
- java - 如何修复运行 Hadoop 程序的 Eclipse 中的 InputBootStrapper 错误?