node.js - Node - 延续本地存储

标签 node.js express node-local-storage

我正在尝试使用 continuation-local-storage 包从不易访问的位置访问当前的快速请求/响应。

我创建了以下中间件:

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);
};

有人有什么想法吗?

提前致谢

标记

最佳答案

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') 

关于node.js - Node - 延续本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34017888/

相关文章:

javascript - 在 then() block 中使用返回 promise 的函数

javascript - 如何检索数据/ key :value pairs from URL-encoded form using POST in express/node. js?

node.js - 执行请求期间 Node CLS 上下文丢失

javascript - 如何删除 Node 本地存储中的所有配额?

javascript - 使用 Octokit 或 GitHub Rest API 上传多个文件

node.js - 如何比较图像并确定哪个内容更多?

javascript - 为什么我的 CSV 没有写入任何数据?

javascript - 带有 ajax 和 Node http 模块的 Node.js 管道流

javascript - Node.js Express 应用程序无法从 dropzone.js 回调重定向