node - continuation-local-storage

时间:2015-12-01 10:18:28

标签: node.js express node-local-storage

我正在尝试使用continuation-local-storage包从一个不易访问的点访问当前的express请求/响应。

我创建了以下中间件:

var createNamespace = require('continuation-local-storage').createNamespace,
    getNamespace = require('continuation-local-storage').getNamespace;

const domain = 'ns.cls';

exports.configure = function(app) {
  createNamespace(domain);

  app.use(function(req, res, next) {
    exports.set(req, res, "callcontext", { req, res });
    next();
  });
};

exports.set = function(req, res, name, value) {
  var namespace = getNamespace(domain);

  namespace.bindEmitter(req);
  namespace.bindEmitter(res);

  namespace.run(() => namespace.set(name, value));
};

exports.get = function(name) {
  var namespace = getNamespace(domain);
  return namespace.get(name);
};

exports.getCallContext = function() {
  return exports.get("callcontext");
};

但是当我尝试访问上下文时,它是未定义的:

var localStorage = require('../middleware/local-storage');

module.exports = function(doc, ctx) {
  var callContext = localStorage.getCallContext();
  console.log("value: " + callContext);
};

有没有人有任何想法?

提前致谢,

标记

1 个答案:

答案 0 :(得分:2)

createNameSpace应该被调用一次。此外,您在线上有错误

exports.set(req, res, "callcontext", { req, res });

应该是

exports.set(req, res, "callcontext", { key: value });

这就是我使用它的方式:
设置

var session = require('continuation-local-storage').createNamespace('session')
app.use(function(req, res, next) {
    session.bindEmitter(req);
    session.bindEmitter(res);

    session.run(function() {
      session.set('req', req);
      next();
    });
  });

获取

var session = require('continuation-local-storage').getNamespace('session')
session.get('req')