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

how request.profile can be used in node.js?

我得到了一个使用 req.profile 阅读的代码 data.How 这可能吗?

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)
    })
  }
}

回购 link: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"
    })
  }
}