微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 node.js 中使用 request.profile?

如何解决如何在 node.js 中使用 request.profile?

我遇到了一个使用 req.profile 读取数据的代码。这怎么可能?

const listNewsFeed = async (req,res) => {
  let following = req.profile.following
  following.push(req.profile._id)
  try{
    let posts = await Post.find({postedBy: { $in : req.profile.following } })
                          .populate('comments.postedBy','_id name')
                          .populate('postedBy','_id name')
                          .sort('-created')
                          .exec()
    res.json(posts)
  }catch(err){
    return res.status(400).json({
      error: errorHandler.getErrorMessage(err)
    })
  }
}

回购链接https://github.com/shamahoque/mern-social/blob/second-edition/server/controllers/post.controller.js

解决方法

键是 middleware。在 Express 中,在请求到达路由处理程序(您所引用的对象)之前,它可以通过一系列中间件,这些中间件可以添加或修改请求或响应对象。

Here 是它设置 req.profile 的地方:

const userByID = async (req,res,next,id) => {
  try {
    let user = await User.findById(id).populate('following','_id name')
    .populate('followers','_id name')
    .exec()
    if (!user)
      return res.status('400').json({
        error: "User not found"
      })
    req.profile = user
    next()
  } catch (err) {
    return res.status('400').json({
      error: "Could not retrieve user"
    })
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。