我读了这篇文章,我试图在我的日志中获取logId,但我做不到,因为asyncLocalStorage.getStore()返回未定义。似乎上下文在MyLogger类中丢失了。如何解决?
这是我的express应用程序
  const asyncLocalStorage = new AsyncLocalStorage();
  app.use((req, res, next) => {
          asyncLocalStorage.run(new Map(), () => {
            asyncLocalStorage.getStore().set("requestId", uuid());
            next();
          });
        });
    
    module.exports.asyncLocalStorage = asyncLocalStorage;这是MyLogger类
   static log(logId, className, text) {
    const { asyncLocalStorage } = require("../server.js");
    const store = asyncLocalStorage.getStore()
    console.log(this._getBaseStaticLog(logId, logTypes.LOG, text, className));
  }发布于 2020-10-14 23:16:39
我解决了这个问题。问题是,由于bodyparser中间件,我丢失了上下文。我在设置上下文之前更改了中间件,现在可以了。是:
app.use((req, res, next) => {
  asyncLocalStorage.run(new Map(), () => {
    asyncLocalStorage.getStore().set("requestId", uuid());
    next();
  });
});
// body parser
app.use(
  bodyParser.json({
    limit: "10mb"
  })
);更改:
// body parser
app.use(
  bodyParser.json({
    limit: "10mb"
  })
);
app.use((req, res, next) => {
  asyncLocalStorage.run(new Map(), () => {
    asyncLocalStorage.getStore().set("requestId", uuid());
    next();
  });
});现在一切都好了)
https://stackoverflow.com/questions/64330910
复制相似问题