如何在Node JS应用中使用express保存请求上下文?

How do you preserve request context in a Node JS App using express?

本文关键字:express 保存 请求 上下文 Node JS 应用      更新时间:2023-09-26

我的请求对象包含一个唯一的id,每个日志在我的应用程序必须有。这个id还必须传播到我从后端调用的任何api。现在,我正在到处传递请求对象。这显然不是一个理想的解决方案。有什么建议吗?

代码流

客户端------->服务器(生成请求id,用于所有日志)----->传递请求id到任何api调用

代码:

app.use(function(req,res,next) {    
  logger.info("My message",req);
});

您可以使用continuationlocal -storage模块。还有一个请求本地模块,它只是延续本地存储之上的一个小层。但是,不要期望本地存储的延续总是完美的……您将遇到CLS上下文无效的边缘情况。

下面是使用continuation-local-storage模块的修改后的解决方案。

这是我的context模块。到目前为止,它只存储路径,请求时间和关联ID,如果它在请求中没有收到一个,它会生成。

'use strict';
const continuation = require('continuation-local-storage');
const cuid = require('cuid');
const appName = require('config').get('app_name');
class Context {
    static setup(req, res, next) {
        const session = continuation.createNamespace(appName);
        session.run(() => {
            session.set('context', new Context(req));
            next();
        });
    }
    constructor(req) {
        this.path = req.path;
        this.corrId = req.headers['x-correlation-id'] || cuid();
        this.requestTime = Date.now();
    }
    static current() {
        return continuation.getNamespace(appName).get('context');
    }
}
module.exports = Context;

我的app.js包括:

const Context = require('./context');
app.use(Context.setup);

之后,任何代码都可以调用Context.current()来获取Express请求的当前上下文。我将使用它来进行一致的日志记录。

考虑到这是我搜索"表达请求上下文"时显示的第一个链接,我想我应该给出一个最近的答案。我认为存储有关请求/响应生命周期的上下文信息的正确位置是根据Express文档在res.locals中。根据另一个SO的回答,req.locals也被使用,但在文档中没有提到这一点,类型定义不允许它开箱使用。