我有一个 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.param
和 app.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/