nodejs / express中的retreive会话信息没有请求变量

时间:2018-02-03 05:08:02

标签: javascript node.js express session

如果我使用express-session会话变量在req.session下可用,例如:

 app.get('/', function(req, res) {
      req.session.myVar = 1;
 }

但是,如果我想在我的应用程序中深深嵌套当前请求的会话,而我没有req变量,那该怎么办?

除了在整个框架中传递req变量作为参数之外,还有另一种方法吗?

2 个答案:

答案 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:

  1. Put the data on req and pass req through your code to the function that needs the data.
  2. Pass the data itself (no need to pass the whole req object if you only need once piece of data.
  3. Create a new object that is specific to this particular request (not shared with other requests or available to other requests) and put the desired data as a property on that object and then pass that object through to the desired code. In an OO world, you can usually put multiple functions as methods on a shared object and then the data is automatically available to all those methods so you don't have to explicitly pass it.
  4. Use a shared scope and closure so that any functions that need access to the data can get it directly from a parent scope.

答案 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');