简体   繁体   English

在 NodeJS 中获取原始 HTTP 响应

[英]Get raw HTTP response in NodeJS

I can get raw HTTP request this way:我可以通过这种方式获取原始 HTTP 请求:

// ...
server.listen(8080);
 
server.on('connection', function(socket) {
  socket.on('data', function(data) {
    console.log(data.toString());
  });
});

But how can I get my raw answer (HTTP-response) in NodeJS?但是我怎样才能在 NodeJS 中得到我的原始答案(HTTP 响应)? I need something like (in my NodeJS, not browser):我需要类似的东西(在我的 NodeJS 中,而不是浏览器中):

HTTP 200 OK
Content-Length: 1000
...

I'm curious what problem you're really trying to solve because there's probably a better way.我很好奇你真正想解决什么问题,因为可能有更好的方法。

But, if you just want to hack into a given response to see exactly what is being sent over that socket, you can monkey patch the socket.write() method to do something like this:但是,如果您只是想侵入给定的响应以查看通过该套接字发送的确切内容,您可以socket.write()方法以执行以下操作:

const app = require('express')();

app.get("/", (req, res) => {
    // monkey patch socket.write
    // so we can log every sent over the socket
    const socket = req.socket;
    socket.origWrite = socket.write;
    socket.write = function(data, encoding, callback) {
        if (Buffer.isBuffer(data)) {
            console.log(data.toString());
        } else {
            console.log(data);
        }
        return socket.origWrite(data, encoding, callback);
    }
    res.cookie("color", "blue");
    res.send("Hi.  This is my http response.")
});

app.listen(80);

When I ran that and made a browser request to that route, I saw this in my console:当我运行它并向该路由发出浏览器请求时,我在控制台中看到了这个:

HTTP/1.1 200 OK
X-Powered-By: Express
Set-Cookie: color=blue; Path=/
Content-Type: text/html; charset=utf-8
Content-Length: 30
ETag: W/"1e-eJoRAEkyvi+cvBVvRkYOHolFbNc"
Date: Wed, 15 Dec 2021 19:43:20 GMT
Connection: keep-alive
Keep-Alive: timeout=5


Hi.  This is my http response.

Which matches exactly what the Chrome debugger shows the http response was on the receiving end of things.这与 Chrome 调试器显示的 http 响应在事物的接收端完全匹配。

I spent a fair amount of time looking for some debug flags built into nodejs that would output this automatically, but could not find any.我花了相当多的时间寻找一些内置在 nodejs 中的调试标志,这些标志会自动 output ,但找不到。 The 'net' module does have some debugging, but it has to do with socket events and lifetime, not with actual data being sent/received. 'net' 模块确实有一些调试,但它与套接字事件和生命周期有关,而不是与发送/接收的实际数据有关。


FYI, you could also "inspect" the raw network data using a network analyzer such as WireShark (there are many others also) which patches into your network adapter and can be configured to watch things and show you exactly what data is being sent/received.仅供参考,您还可以使用诸如 WireShark 之类的网络分析器(还有许多其他网络分析器)“检查”原始网络数据,这些分析器会修补到您的网络适配器中,并且可以配置为观察并准确显示正在发送/接收的数据.

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

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