Is it possible to get the current request that is being served by node.js? Is it possible to get the current request that is being served by node.js? express express

Is it possible to get the current request that is being served by node.js?


An interesting way to do this would be the new Domains feature.http://nodejs.org/api/domain.html

Domains, while providing excellent error recovery, can be used as a type of "Thread Local Storage" - basically storing data for each request.

Create some middleware that adds every request/response to a domain.

app.use(function(req, res, next) {  var reqd = domain.create();  reqd.add(req);  reqd.add(res);  reqd._req = req; // Add request object to custom property  // TODO: hook error event on reqd (see docs)  next();});

In the log function, you can now get the current domain and pull out the request object.

function log_message(level, message) {  // Pull the request from the current domain.  var request = process.domain._req;  // TODO: log message};

Domains are still experimental, but it doesn't sound like much will change between now and the 1.0 release.


Similar to the domains answer, it's now a lot easier to do this using continuation-local-storage: https://datahero.com/blog/2014/05/22/node-js-preserving-data-across-async-callbacks/

At DataHero we save a transaction id, user id, and session id with all log messages. You don't need to pass the request object all the way down, so it helps keep your models / business layer clean, too.


create a midleware:

app.use(function(req, res, next) {       var tid = uuid.v4();     var cls = require('continuation-local-storage');       var namespace = cls.createNamespace('com.storage');      var pre_ip;          if(get_ip(req))          { ip_info= get_ip(req).clientIp;              pre_ip=ip_info          }          namespace.bindEmitter(req);          namespace.bindEmitter(res);        namespace.run(function() {               console.log(logobj);              namespace.set('tid', tid);              namespace.set('ip',ip_info);           namespace.set('logobj',logobj);                 next();          });      });

And use it :

var cls = require('continuation-local-storage'); var namespace = cls.getNamespace('com.storage');      namespace.get('ip');