javascript - NodeJS 从其他函数填充 "req"

标签 javascript node.js express

我有一个 NodeJS + Express 服务器设置和一个看起来像这样的路由器:

app.route('/clients/:clientId)
    .get(users.ensureAuthenticated, clients.read)
    .put(users.ensureAuthenticated, clients.hasAuthorization, clients.update)
    .delete(users.ensureAuthenticated, clients.hasAuthorization, clients.delete);

app.param('clientId', clients.clientByID);

我的问题是 users.ensureAuthenticated 用当前用户 req.user 填充 req 参数。

基本上它是这样做的:req.user = payload.sub;(还有一些其他的背景资料)

然后 req.user 在以下函数中可用,例如clients.update,但不在 clients.clientByID 中。

我知道我可以再次在 clients.clientByID 中执行 users.ensureAuthenticated ,但这会执行代码两次并在服务器上增加额外的负载,对吧?我想一定有另一种方式,但我在 express 的文档中找不到任何东西。

我想知道如何访问 clients.clientByID 中的 req.user 而不执行 users.ensureAuthenticated< 中的代码 两次。

最佳答案

根据您的问题,我假设您希望在执行 clients.clientByID 之前执行 users.ensureAuthenticated。这可以通过使用 app.use 功能来实现。 app.use 处理程序将在 app.paramapp.route 处理程序之前执行。

例如:

var express = require('express');
var app = express();

app.use('/user', function(req, res, next) {
    console.log('First! Time to do some authentication!');
    next();
});

app.param('id', function(req, res, next, id) {
    console.log('Second! Now we can lookup the actual user.');
    next();
});

app.get('/user/:id', function(req, res, next) {
    console.log('Third! Here we do all our other stuff.');
    next();
});

app.listen(3000, function() {
});

关于javascript - NodeJS 从其他函数填充 "req",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33258315/

相关文章:

javascript - 用跨度包围 2 个同级元素

Javascript 显示/隐藏链接不起作用

javascript - appendChild() 从导入的模板中删除内容

node.js - 如何检查 mongoose 对象引用是否包含匹配的字段?

node.js - 在预保存 Hook 中更新

node.js - NodeJS/express 4 : Can't set headers after they are sent while writing cookie

javascript - 使用 jQuery .html() 时 IE8 会追加

node.js - Docker:如何使用 selenium 服务器进行 nightwatchJS 测试?

node.js - neo4j 是否有可能限制收集的数据?

javascript - 如何在 Express 上捕获 M-SEARCH 请求?