请求中的 nodejs express 配置文件 属性

nodejs express profile property in request

我对一种用法感到很困惑:

在路由文件中:

  app.param('userId', users.load);

和 users.load 函数:

exports.load = function (req, res, next, id) {
    var options = {
        criteria: { _id : id }
    };
    User.load(options, function (err, user) {
        if (err) return next(err);
        if (!user) return next(new Error('Failed to load User ' + id));
        req.profile = user;
        next();
    });
};

这里route应该有userId去response,但是作者这里为什么用req.profileprofile 不是 属性。

有人可以帮忙吗?

谢谢。

代码的作用是这样的:对于具有 userId 参数的路由(即看起来类似于此的路由:/user/:userId),Express 将调用 load() function before 调用路由处理程序。

加载函数从数据库中加载属于userId的用户配置文件,并将其添加到req作为新创建的属性 req.profile.

.profile 属性 名称是作者任意命名的,并证明了向 req (或 res 添加属性是完全有效的事实很重要,但惯例是将这些属性添加到 req).

在路由处理程序中,您可以使用 req.profile。它基本上是一种将数据从中间件和 app.param() 实现传播到路由处理的其他部分的方法。