Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get request body from node.js's http.IncomingMessage

Tags:

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

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

Request's method, URL and headers are printed correctly, but r.read() is always NULL. I can say it's not a problem in how the request is made, because content-length header is greater than zero on server side.

Documentation says r is a http.IncomingMessage object that implements the Readable Stream interface, so why it's not working?

like image 725
lorenzo-s Avatar asked Jun 23 '15 15:06

lorenzo-s


People also ask

What is HTTP createServer ()?

The http. createServer() method turns your computer into an HTTP server. The http. createServer() method creates an HTTP Server object. The HTTP Server object can listen to ports on your computer and execute a function, a requestListener, each time a request is made.


1 Answers

'readable' event is wrong, it incorrectly adds an extra null character to the end of the body string

Processing the stream with chunks using 'data' event:

http.createServer((r, s) => {     console.log(r.method, r.url, r.headers);     let body = '';     r.on('data', (chunk) => {         body += chunk;     });     r.on('end', () => {         console.log(body);         s.write('OK');          s.end();      }); }).listen(42646);  
like image 94
BigMan73 Avatar answered Nov 12 '22 16:11

BigMan73