NODE JS-EXPRESS:当它适用于 GET 时,无法从 HTTP 上下文中检索 POST 和 PUT 请求的值

reg*_*ank 7 httpcontext node.js express

在 Node.js 和 Express 框架中,当它适用于 GET 时,我无法从 HTTP 上下文中检索 POST 和 PUT 请求的值。我正在使用 httpContext 设置唯一的 requestId 标识符,以便在记录跟踪 API 请求时可以使用它。

我发现 HttpContext 可以被中间件中的其他一些包重置,是否有更好的方法来存储可以在所有模块中访问的请求范围的数据。

app.js 文件



        const app = express();
        app.use(httpContext.middleware);
        //Assign unique identifier to each req
        app.use(function (req, res, next) {
          let test = uuidv1();
          httpContext.set("reqId", test);
          next();
        });

        const PORT = process.env.PORT || 3001;
        Connection.setupPool();
        app.use(express.json());
        app.use(helmet());
        if (app.get("env") === "development") {
          app.use(morgan("tiny"));
        }

        //use to access a resource in the root through url
        app.use(express.static("resource"));

        app.use("/users", userRouter);
        //Code For Instagram authentication Using Passport
        logger.info("End-Instagram Authentication Configuration");
        app.listen(PORT, () => {
          logger.info(`app running port ${PORT}`);
        });
Run Code Online (Sandbox Code Playgroud)

我从 httpContext 中检索 reqId 的代码

记录器.js

   message = httpContext.get("reqId") ? "RequestId: " + 
             httpContext.get("reqId")+" "+ message: ""+ message ;
Run Code Online (Sandbox Code Playgroud)

小智 11

我希望这个解决方案可以解决您的问题,并为遇到此问题的任何人节省很多时间

你可以使用 bindEmitter 来解决这个问题

app.use((req, res, next) => {
    httpContext.ns.bindEmitter(req);
    httpContext.ns.bindEmitter(res);
    var requestId = req.headers["x-request-id"] || uuidv4();
    httpContext.set("requestId", requestId);
    console.log('request Id set is: ', httpContext.get('requestId'));
    next();
});
Run Code Online (Sandbox Code Playgroud)

  • 如果我理解正确的话,对请求进行排队的中间件会混淆 httpContext,因为它不再将消息与正确的上下文关联起来。需要绑定到 `req`/`res` 事件以确保在实际处理请求时选择正确的上下文。 (2认同)

Shi*_*nha 10

我有相同的问题。尝试了上面的 bindEmitter 解决方案,但没有奏效。

经过一些跟踪和错误 REF#1'Content-Type': 'application/json'从我的客户端 POST 调用中删除标头后,允许设置/保留上下文中的值。

这让我怀疑body-parser(v1.19.0)中间件和express-http-context(v1.2.3)交互方式存在问题。

当我颠倒中间件的顺序时,body-parserexpress-http-contexthttpContext 按预期工作之前(无需执行 REF#1 )例如:

app.use(bodyParser.json()); //must come before
app.use(httpContext.middleware);
Run Code Online (Sandbox Code Playgroud)