GLOBAL data per HTTP/Session request?

前端 未结 5 2222
刺人心
刺人心 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:21

    Per request, I think what you're after could be done with ordinary closures. For example, you'd define your custom functions in module that takes a req argument:

    util_funcs.js:

    module.exports = function( req ){
      return {
        customFunctionThatRequiresReq: function(){ console.info( req ) },
        otherFunctionThatRequiresReq:  function(){ console.log( req ) }
      };
    };
    

    Then wherever you depend on those functions (presumably some middleware elsewhere in the application), you can just require them in context:

    var someMiddleWare = function( req, res, next ){
    
      var utils = require( 'util_funcs.js' )( req );
    
      utils.customFunctionThatRequiresReq();
      utils.otherFunctionThatRequiresReq();
    
    }; 
    

    This allows you to avoid littering your function args with req, and no dubious globals.

    0 讨论(0)
  • 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!

    0 讨论(0)
  • 2021-01-06 00:33

    if i'm right to understood your question you can try to make global variable in node js which can stored username

    you can use global array with unique id

    suppose user1 hit the http request therefore you store like this in node js

    if(!username)
       username = [];
    
    if(!uniqId)
       uniqId = 0;
    uniqId++;
    
    username[uniqId] = 'xyz';
    

    similar like this it is working

    0 讨论(0)
  • 2021-01-06 00:47

    have you tried using a cookies? set the cookie to the browser and then everytime there is a request, you would know the user by its cookie.. you may use 'cookie-parser' node library.

    0 讨论(0)
  • 2021-01-06 00:48

    Yes, with some caveats. You're looking for a module called continuation-local-storage.
    This allows you to keep arbitrary data for the remainder of callbacks for the current request, and access it in a global fashion.
    I wrote a blog post about it here. But the gist is this:

    1. Install cls: npm install --save continuation-local-storage
    2. Create a namespace for your app (at the top of the main file for your app)

      var createNamespace = require('continuation-local-storage').createNamespace, 
          namespace = createNamespace('myAppNamespace');
      
    3. Create a middleware that runs downstream functions in the cls (continuation-local-storage) namespace

      var getNamespace = require('continuation-local-storage').getNamespace,
          namespace = getNamespace('myAppNamespace'),
      
      app.use(function(req, res, next) {    
        // wrap the events from request and response
        namespace.bindEmitter(req);
        namespace.bindEmitter(res);
      
        // run following middleware in the scope of the namespace we created
        namespace.run(function() {
          namespace.set(‘foo’, 'a string data');
          next();
        });
      });
      
    4. Since you ran next within namespace.run, any downstream function can access data in the namespace

      var getNamespace = require('continuation-local-storage').getNamespace,
          namespace = getNamespace('myAppNamespace');
      
      // Some downstream function that doesn't have access to req...
      function doSomething() {
        var myData = namespace.get('foo');
        // myData will be 'a string data'
      }
      
    5. There is the caveat that certain modules can "lose" the context created by cls. This means that when you go to lookup 'foo' on the namespace, it won't have it. There are a few ways to deal with this, namely using another module like cls-redis, cls-q, or binding to the namespace.

    0 讨论(0)
提交回复
热议问题