我有以下中间件:
const mongoose = require('mongoose');
module.exports = function(req, res, next) {
const keys = Object.keys(req.params);
keys.forEach(elem => {
if (
(elem.includes('id') || elem.includes('Id')) &&
!mongoose.Types.ObjectId.isValid(req.params[elem])
)
return res
.status(400)
.json({ msg: `id: ${req.params[elem]} is invalid` });
});
next();
};
在获取请求中调用它:
// @route GET api/movies/:id
// @desc Get a movie with specified id from db
// @access Public
router.get('/:id', checkId, async (req, res) => {
const movie = await Movie.findById(req.params.id);
res.json(movie);
});
当我在邮递员中使用无效ID(例如1234)发出请求时,我收到的正确响应是400,带有msg:“ id 1234 is invalid”,但执行仍然传递到要求的回调代码,并引发错误当我尝试使用无效ID访问数据库时。
所以问题是,即使中间件已经随400一起返回,为什么中间件仍允许执行next()?
答案 0 :(得分:1)
您需要通过致电next("some-error")
来告诉路由器有问题。例如,您可以这样做:
module.exports = function(req, res, next) {
const keys = Object.keys(req.params);
keys.forEach(elem => {
if (
(elem.includes('id') || elem.includes('Id')) &&
!mongoose.Types.ObjectId.isValid(req.params[elem])
) {
res
.status(400)
.json({ msg: `id: ${req.params[elem]} is invalid` });
return next("invalidinput");
}
});
next();
};
或者,如果您愿意,可以通过在路由器外部设置结果来更通用一些,
在您的中间件中:
module.exports = function(req, res, next) {
const keys = Object.keys(req.params);
keys.forEach(elem => {
if (
(elem.includes('id') || elem.includes('Id')) &&
!mongoose.Types.ObjectId.isValid(req.params[elem])
) {
// === Report the error and let the router handle it
return next({
type: "invalidinput",
msg: `id: ${req.params[elem]} is invalid`
);
}
});
next();
};
然后在路由器底部:
// handle any errors
router.use(err, req, res, next) => {
if (err) {
if (err.type === "invalidinput") {
return req.status(400).json({msg: err.msg});
}
else {
return res.status(500).json({msg: "Internal error."});
}
}
return next();
}
答案 1 :(得分:0)
这里的另一种可能的解决方案是将forEach转换为经典的for循环,从而使该中间件同步运行
module.exports = function(req, res, next) {
const keys = Object.keys(req.params);
for (let i = 0; i < keys.length; i++) {
if (
(keys[i].includes('id') || keys[i].includes('Id')) &&
!mongoose.Types.ObjectId.isValid(req.params[keys[i]])
)
return res
.status(400)
.json({ msg: `id: ${req.params[keys[i]]} is invalid` });
}
next();
};