如果有人像我一样来到这里,寻找传递隐式上下文并使用 express。
我最终为此使用了 express-http-context ( https://www.npmjs.com/package/express-http-context )
从文档:
var express = require('express');
var httpContext = require('express-http-context');
var app = express();
// Use any third party middleware that does not need access to the context here, e.g.
// app.use(some3rdParty.middleware);
app.use(httpContext.middleware);
// all code from here on has access to the same context for each request
获取用户或您想要保留的任何数据:
// Example authorization middleware
app.use((req, res, next) => {
userService.getUser(req.get('Authorization'), (err, result) => {
if (err) {
next(err);
} else {
httpContext.set('user', result.user)
next();
}
});
});
在其他需要价值的地方:
var httpContext = require('express-http-context');
// Somewhere deep in the Todo Service
function createTodoItem(title, content, callback) {
var user = httpContext.get('user');
db.insert({ title, content, userId: user.id }, callback);
}