我正在使用 npm 请求上下文。我收到此错误:
未找到设置属性提供者的活动上下文
当我尝试使用set()函数设置上下文时。
代码如下:
const contextService = require("request-context");
router.use('/*', (req, res, next) => {
Provider.findOne({ _id: req.providerId }, (err, provider) => {
if (provider) {
app.use(contextService.middleware('provider'));
console.log(contextService.getContext('provider')); // undefined
contextService.set('provider', res.locals.provider); // ERROR - No active context found to set property provider
}
next();
});
}
request-context/lib/index.js我在文件中跟踪此问题和文件中的方法时发现的问题app.use()序列express/lib/application.js
- 此行
app.use(contextService.middleware('provider'));返回一个函数runInContextMiddleware(req, res, next),app.use()但它从未在内部发出app.use。 - 在
app.use,
if (!fn || !fn.handle || !fn.set) {
return router.use(path, fn);
}
其中,fn isrunInContextMiddleware(req, res, next)和handle&set属性未定义,fn因此它不执行fn.emit('mount', this);
- 结果,永远不会设置上下文,并且这一行
console.log(contextService.getContext('provider'));给出了undefined. - 最后,
setContext()调用getCurrent(current)并存储domain.active在 中current,即null.
这就是我面临错误的方式。