javascript - Node js:当我从快速路由调用异步函数时,为什么会出现```TypeError: Cannot read property 'json' of undefined```?
问题描述
当满足某些条件时,我正在从快速路由调用异步函数。但是,当调用递归函数时,我得到了TypeError: Cannot read property 'json' of undefined
. 为什么在路由外部调用时,递归函数中未定义 .json() 方法?有办法补救吗?
快速路由调用递归函数
asyncHandler 函数
const asyncHandler = (callback) => {
return async (req, res, next) => {
try {
await callback(req, res, next);
} catch (error) {
next(error);
console.log(error);
}
};
}
router.patch( "/user/match/:id", authenticateUser, asyncHandler(async (req, res, next, error) => {
const errors = validationResult(req);
const user = await User.findOne({ _id: req.params.id });
if (!errors.isEmpty()) {
const errorMessages = errors.array().map((error) => error.msg);
return res.status(400).json({ error: errorMessages });
}
const updateObject = req.body.likes;
console.log(updateObject)
const likedUser = await User.findOne({ _id: updateObject });
if (req.body.likes) {
await User.findOneAndUpdate( { _id: req.params.id }, { $push: { likes: updateObject._id } });
//function being called.
recursive(likedUser, user)
} else if (req.body.dislikes) {
await User.findOneAndUpdate({ _id: req.params.id }, { $push: { dislikes: req.body.dislikes._id } },
function (error, doc) {
if (error) {
return res.json({ success: false, message: err.message });
}
res.json({ message: "Nope" });
return res.status(204).end();
}
);
}
})
);
递归函数
const recursive = async (match, user, req, res, error, next) => {
console.log(match.likes)
const newUser = {
_id: user._id,
firstName: user.firstName,
path: user.path
};
console.log(newUser, "new user")
const newMatch = {
_id: match._id,
firstName: match.firstName,
path: match.path
};
console.log(newMatch, "new match")
try {
for (let i = 0; i < match.likes.length; i ++) {
console.log(match.likes[i], 'like._id');
if ( user._id.equals(match.likes[i]) ) {
await User.findOneAndUpdate({ _id: user._id }, { $push: { matches: newMatch } });
await User.findOneAndUpdate({ _id: match._id }, { $push: { matches: newUser } });
const newConversation = new Conversation({ members: [user._id, match._id] });
console.log(newConversation, "New conversation");
if (error) {
console.log(error)
res.status(500).json(error);
} else {
const savedConversation = await newConversation.save();
console.log(savedConversation);
res.status(200).json(savedConversation, { message: 'Its a match!' }).end();
}
} else {
console.log("match")
res.json({ message: 'Liked' })
}
};
} catch(error) {
console.log(error)
return res.json(error);
}
};
解决方案
您的recursive
函数有 6 个参数:match
、user
、req
、res
、error
和next
。但是,您的recursive
电话看起来像这样:recursive(likedUser, user)
. 您只向它发送 2 个参数。因此,在设置match
和user
参数时,其他 4 个未分配并保留为null
。
然后,当代码尝试res.json
在您的递归函数中使用时,它会失败,因为res
设置为null
并且显然null
没有名为 的方法json
。如果要解决此问题,则需要将变量(req、res 等)实际传递到递归函数调用中。
推荐阅读
- python - Kivy - 一行被复制/镜像,我看不到原因
- macos - 使用 ffmpeg 为 AppStore 缩放应用预览视频
- swift - 如何设置将在我的应用程序中运行的键盘观察器?
- javascript - 在 JavaScript 中读取 XML 标记名称
- php - 在 Woocommerce 产品中添加按修改日期排序
- javascript - Node.js - 带有 GET 处理程序的简单 Express 服务器不起作用
- javascript - 检查 jquery 的多个输入的值是否为空的更短方法
- android - 一个 Activity 两个或多个 NavHostFragment
- node.js - gulp 将任务组合到默认命令中
- r - 如何使用 apply 创建多个多项式变量?