简体   繁体   English

Node http 模块 - 拦截 http.request 函数时获取请求体

[英]Node http module - get request body when intercepting http.request function

I'm writing an internal logger that intercepts Node's http module by overriding the request method.我正在编写一个内部记录器,它通过覆盖request方法来拦截 Node 的http模块。
This is what I have so far:这是我到目前为止:

const http = require('http');

const oldHttpRequest = http.request;
http.request = (options, callback) => {
    const newCallback = (res) => {
        // Do logging logic here

        return callback(res);
    }

    return oldHttpRequest(options, newCallback);
};

From options and res objects I'm able to retrieve everything I need (method, path, request headers, response headers, response body, etc..).optionsres对象中,我可以检索我需要的所有内容(方法、路径、请求标头、响应标头、响应正文等)。
Everything but the outgoing request body.除了传出请求正文之外的所有内容。

What am I missing?我错过了什么?

Managed to do it, posting the solution if anyone is interested.设法做到了,如果有人感兴趣,请发布解决方案。

I ended up having to monkey patch the write method as well:我最终也不得不修补 write 方法:

const http = require('http');

const oldHttpRequest = http.request;

http.request = (options, callback) => {
    const requestBodyChunks = [];
    const newCallback = (res) => {
        // Do logging logic here
        console.log('Request body:', requestBodyChunks.join())

        return callback(res);
    }

    const clientRequest = oldHttpRequest(options, newCallback);
    const oldWrite = clientRequest.write.bind(clientRequest);

    clientRequest.write = (data: any) => {
        requestBodyChunks.push(data.toString());
        return oldWrite(data);
    };

    return clientRequest;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM