GLOBAL data per HTTP/Session request?

前端 未结 5 2288
刺人心
刺人心 2021-01-05 23:56

QUESTION:

Is there any way to create a variable storage in per session/http request? The variable must be globally accessible and different

5条回答
  •  余生分开走
    2021-01-06 00:32

    You can an unstable feature: nodejs domains

    I do this on top of my head so read the docs and figure out really how it works ;)

    Create a middleware high up in the hierarchy that will create a domain and run the remaining request handlers in the context of that domain:

    app.use(function(req, res, next) {
      var domain = domain.create();
      domain.req = req;
      domain.run(next);
    });
    

    Then anywhere in your handlers, you can access the current request with:

    var req = process.domain.req;
    

    Again, read the docs, I'm really not sure about all this but this is one approach!

提交回复
热议问题