简体   繁体   中英

Get raw HTTP response in NodeJS

I can get raw HTTP request this way:

// ...
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? I need something like (in my NodeJS, not browser):

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:

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.

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. The 'net' module does have some debugging, but it has to do with socket events and lifetime, not with actual data being sent/received.


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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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