Get request body from node.js http.IncomingMessage

I am trying to implement a simple HTTP endpoint for an application written in node.js. I created an HTTP server, but now I'm stuck in reading the body of the request content:

http.createServer(function(r, s) {
    console.log(r.method, r.url, r.headers);
    console.log(r.read());
    s.write("OK"); 
    s.end(); 
}).listen(42646);

The request method, URLs and headers are typed correctly, but r.read()always NULL. I can say that this is not a problem in how the request is made, because the header is content-lengthgreater than zero on the server side.

The documentation says r - this is an object http.IncomingMessagethat implements the Readable Stream interface, so why doesn't it work?

+4
source share
1 answer

, , . r ( node.js, ...) async-:

http.createServer(function(r, s) {
    console.log(r.method, r.url, r.headers);
    var body = "";
    r.on('readable', function() {
        body += r.read();
    });
    r.on('end', function() {
        console.log(body);
        s.write("OK"); 
        s.end(); 
    });
}).listen(42646);
+9

All Articles