node-continuation-local-storage icon indicating copy to clipboard operation
node-continuation-local-storage copied to clipboard

Access to req, res objects

Open samuelbodin opened this issue 6 years ago • 2 comments

From the examples it's not entirely clear to me how I can access data that I pass to the bindEmitter() function. In the code below I use the createServer from the http module. Now my question is, how can I save the request and response objects to later access them from my foo function?

var createNamespace = require('continuation-local-storage').createNamespace;
var session  = createNamespace('some namespace');
var http = require('http');

function foo() {
    // How do I access res/req from here?
}

http.createServer(function (req, res) {
  session.bindEmitter(req);
  session.bindEmitter(res);

  // Call foo without passing in req and res.
  foo();
}).listen(8000);

samuelbodin avatar Aug 02 '18 17:08 samuelbodin

var createNamespace = require('continuation-local-storage').createNamespace;
var session  = createNamespace('some namespace');
var http = require('http');


http.createServer(function (req, res) {
  session.bindEmitter(req);
  session.bindEmitter(res);

  // Call foo without passing in req and res.
  foo();

  function foo() {
      console.log(req, res);
  }
}).listen(8000);

like this?

carlisliu avatar Aug 06 '18 02:08 carlisliu

bindEmitter only ensures continuation through event emitters. It doesn't expose anything to the context.

What you need is to do something like session.set('request', req) and then session.get('request') later.

Qard avatar Aug 08 '18 21:08 Qard