如果我使用express-session
会话变量在req.session
下可用,例如:
app.get('/', function(req, res) {
req.session.myVar = 1;
}
但是,如果我想在我的应用程序中深深嵌套当前请求的会话,而我没有req
变量,那该怎么办?
除了在整个框架中传递req
变量作为参数之外,还有另一种方法吗?
答案 0 :(得分:1)
Is there another way besides passing in the req variable as a parameter all across the framework?
No, not really. A node.js server (that uses any asynchronous operations) can have multiple requests in flight at the same time. So, any request-specific data that you want to access has to come from an object that is associated with this particular request and only this specific request. You can't put it in globals because those can be intermixed from different requests. You have several options, but ultimately you have to pass the data through your functions to wherever it is needed -there is no shortcut here. Here are several options:
req
and pass req
through your code to the function that needs the data.req
object if you only need once piece of data.答案 1 :(得分:0)
我的解决方案是使用Continuation-local-storage作为此类问题中所述的快递中间件NodeJS TransactionID with Continuation-local-storage
import * as cls from "continuation-local-storage";
cls.createNamespace('mynamespace');
app.use((req, res, next) => {
let session = cls.getNamespace('mynamespace');
session.bindEmitter(req);
session.bindEmitter(res);
session.run(function() {
session.set('req', req);
next();
});
});
以后需要时:
var session = cls.getNamespace('mynamespace');
var req = session.get('req');