【问题标题】:How to get the body of a Request in OnResponse hook of Fastity Reply From如何在 Fastity 回复的 OnResponse 钩子中获取请求的正文
【发布时间】:2022-07-29 00:30:03
【问题描述】:

我在一个充当代理的服务中使用Fastify HTTP proxy,该代理需要检查客户端和目标服务器之间交互中的特定请求/响应。 我发现这个解决方案使用了onResponse 钩子:

const fastifyProxyLib = require("@fastify/http-proxy");

register(fastifyProxyLib, {
        ...proxyConfig, //some config
        upstream, //some url
        preHandler: async ({ url, body }) => {
          //Do something for specific url and body
        }
        replyOptions: {
          onResponse: (request, reply, res) => {
            console.log(res);
            reply.code(200).send(res);
          },
        }, 
}

一切正常,但我无法获取res 的主体以检查其有效负载中的内容。响应正确到达我使用axios 的客户端,并且我能够看到正确的正文。在reply.body 内部,我得到了初始请求的正文。如何检查res

【问题讨论】:

    标签: node.js interceptor fastify fastify-reply-from fastify-http-proxy


    【解决方案1】:

    res 参数是一个流,所以你需要使用它:

        onResponse: (request, reply, res) => {
          let data = '';
          res.on('data', chunk => {
            data += chunk;
          })
          res.on('end', () => {
            console.log('data is: ' + data);
            reply.code(200).send(data);
          })
        },
    

    添加onResponse 钩子也应该可以工作,而无需使用res 对象。 https://www.fastify.io/docs/latest/Reference/Hooks/#onresponse

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-27
      • 2021-09-05
      • 2015-08-10
      • 2021-07-22
      • 2021-10-29
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多