NodeJS Express,添加事务ID

伙计们,试图为每个API调用设置一个事务ID。 以下工作:

var cls = require('continuation-local-storage'); var uuid = require('node-uuid'); var namespace = cls.createNamespace('foo'); var tokenMiddleware = function tokenMiddleware(req, res, next){ namespace.bindEmitter(req); namespace.bindEmitter(res); namespace.run(function() { namespace.set('tid', tid); next(); }); }; 

现在,当我尝试添加额外的信息(从mongo返回)时,会丢失上下文:

 var cls = require('continuation-local-storage'); var uuid = require('node-uuid'); var namespace = cls.createNamespace('foo'); var tokenMiddleware = function tokenMiddleware(req, res, next){ mongo.fetchId(authId, function (result) { namespace.bindEmitter(req); namespace.bindEmitter(res); namespace.run(function() { namespace.set('tid', tid); namespace.set('somethingfromDB',result.something); next(); }); }); }; 

事务ID是不可用下来,其未定义…第一个例子是如何工作,第二个不是?

我究竟做错了什么? 我怀疑这个问题必须在next()上下文中做些什么。 Express v4。

谢谢!

我有使用快递类似的问题。 据我所知,mongo模块覆盖请求和响应函数。 一旦你在数据库调用中,你会发现这些对象不再是你期望的那样。 我的解决scheme是将其分解成2个独立的函数,它允许您显式地将它们传递给db函数。

 var tokenMiddleware = function tokenMiddleware(req, res, next){ var callDB = function (req, res, namespace) { mongo.fetchId(authId, function (result) { namespace.bindEmitter(req); namespace.bindEmitter(res); namespace.run(function() { namespace.set('tid', tid); namespace.set('somethingfromDB',result.something); next(); }); }); }); callDB(req, res, namespace) }; 

尝试设置SomethingfromDB承诺。 请参阅https://www.promisejs.org/或尝试在设置了somethingfromdb之后分配tid

 var cls = require('continuation-local-storage'); var uuid = require('node-uuid'); var namespace = cls.createNamespace('foo'); var tokenMiddleware = function tokenMiddleware(req, res, next){ mongo.fetchId(authId, function (result) { namespace.bindEmitter(req); namespace.bindEmitter(res); namespace.run(function() { namespace.set('somethingfromDB',result.something); namespace.set('tid', tid); next(); }); }); }; 

希望这可以帮助