You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express中间件拦截响应并与微服务结果对比时的JSON转换问题求助

Express中间件拦截响应并与微服务结果对比时的JSON转换问题求助

我正在用NodeJS和Express API编写中间件,想要获取响应体并与另一个微服务的结果进行对比,这是替换当前API流程的一部分。

我现在拿到的响应体是Buffer类型,即使使用toString方法转换,还是无法把数据转换成有效的JSON。

我也尝试过监听write、finish、end这类事件,但都遇到了同样的Buffer转换问题。有没有大佬能指点下我可能哪里错了,或者有没有其他方法能实现这个需求?

const microserviceCompareMiddleware = async (req, res, next) => {
  // Clone the request to send it to the new microservice
  const requestData = {
    method: req.method,
    url: req.originalUrl,
    headers: req.headers,
    data: req.body,
  };

  // Capture the response of the current microservice
  const originalSend = res.send;
  res.send = function (body) {
    // Store the response from the current microservice
    let currentResponse = body;

    // If response is a Buffer, convert it to string
    if (Buffer.isBuffer(currentResponse)) {
      currentResponse = currentResponse.toString("utf-8");
    }

    try {
      // Try to parse JSON
      currentResponse = JSON.parse(currentResponse);
    } catch (error) {
      logger.warn(`⚠️ Response is not a valid JSON: ${currentResponse}`);
    }

    // Restore the send method to avoid issues
    originalSend.call(this, body);

    // Call the new microservice asynchronously
    (async () => {
      try {
        const newResponse = await axios({
          method: requestData.method,
          url: `http://localhost:8080/v1${requestData.url}`,
          headers: requestData.headers,
          data: requestData.data,
        });

        // Perform deep comparison of the responses
        if (!_.isEqual(JSON.parse(currentResponse), newResponse.data)) {
          logger.error(`[DISCREPANCY DETECTED] - Endpoint: ${requestData.url}`);
          logger.error(
            `Current Microservice Response:`,
            JSON.parse(currentResponse)
          );
          logger.error(`New Microservice Response:`, newResponse.data);
        }
      } catch (error) {
        logger.error(
          `[ERROR CALLING NEW MICROSERVICE] ${requestData.url}`,
          error.message
        );
        console.log(error);
      }
    })();
  };

  next();
};

备注:内容来源于stack exchange,提问作者Gabriel Baierle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 11:50:29