首页 > 解决方案 > 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);
  }
}; 

标签: javascriptnode.jsasync-await

解决方案


您的recursive函数有 6 个参数:matchuserreqreserrornext。但是,您的recursive电话看起来像这样:recursive(likedUser, user). 您只向它发送 2 个参数。因此,在设置matchuser参数时,其他 4 个未分配并保留为null

然后,当代码尝试res.json在您的递归函数中使用时,它会失败,因为res设置为null并且显然null没有名为 的方法json。如果要解决此问题,则需要将变量(req、res 等)实际传递到递归函数调用中。


推荐阅读