开发者问题收集

如果我在 Express Gateway 应用中记录 http 响应,它不会显示响应数据

2019-06-20
272
  1. 我使用 express 网关代理 http 请求。
  2. 我制作了一个插件(中间件)来记录 http 响应。
  3. 日志显示 ExpressJS 响应对象,但我找不到从 serviceEndpoints 发回的数据。

  4. 我尝试记录“res.body”,但它显示未定义

  5. 此环境是带有节点 8.9.4-alpine 的 docker 容器
  6. Express 网关版本:“^1.9.1”

system.config.json


"plugins": {
    "logger": {
        "package": "logger"
    },

记录器插件:


    const stringify = require('json-stringify-safe');
    module.exports = {
      name: 'logger',
      init: function (pluginContext) {
        pluginContext.registerGatewayRoute(
          (gatewayExpressApp) => {
            gatewayExpressApp.use((req, res, next) => {
              res.on('finish', function () {
                console.log('response: %s', stringify(res));
              });
              next();
            });
          }
        );
      }
    };

res 对象显示:

    {
        "domain": null,
        "_events": {
            "finish": [null, null, null]
        },
        "_eventsCount": 5,
        "output": [],
        "outputEncodings": [],
        "outputCallbacks": [],
        "outputSize": 0,
        "writable": true,
        "_last": true,
        "upgrading": false,
        "chunkedEncoding": false,
        "shouldKeepAlive": false,
        "useChunkedEncodingByDefault": false,
        "sendDate": true,
        "_removedConnection": false,
        "_removedContLen": false,
        "_removedTE": false,
        "_contentLength": null,
        "_hasBody": true,
        "_trailer": "",
        "finished": true,
        "_headerSent": true,
        "socket": null,
        "connection": null,
        "_header": "HTTP/1.1 200 OK\r\nx-powered-by: Express\r\ntimezone-offset: +0:0\r\ntimezone: UTC\r\ncontent-type: application/json; charset=utf-8\r\ncontent-length: 803\r\netag: W/\"323-lP/wh6xQz1k1vBMgrvl3whFu1vA\"\r\ndate: Thu, 20 Jun 2019 08:00:24 GMT\r\nconnection: close\r\n\r\n",
        "_sent100": false,
        "_expect_continue": false,
        "req": {
    ...
        }
        "locals": {},
        "statusCode": 200,
        "statusMessage": "OK"
    }

我想看这个

{
    "status": "success",
    "data": {
        "rows": [],
        "rowLength": 0,
        "pageState": null
    },
    "error": ""
}
1个回答

我遇到了同样的问题。以下是解决方案:

    const write = res.write;
    res.write = (data) => {
      res.data = JSON.parse(data);
      res.write = write;
      return res.write(data);
    };

    res.once("finish", () => {
      console.log(res.data);
    });
Aytuğ Ulış
2023-03-02