Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST Request using req.write() and req.end()

Tags:

node.js

I'm trying to do HTTP POST using the the request module from a node server to another server.

My code looks something like,

var req = request.post({url: "http://foo.com/bar", headers: myHeaders});
...
...
req.write("Hello");
...
...
req.end("World");

I expect the body of the request to be "Hello World" on the receiving end, but what I end up with is just "".

What am I missing here?

Note: The ellipsis in the code indicates that the write and the end might be executed in different process ticks.

like image 341
Gautham Badhrinathan Avatar asked Apr 14 '26 14:04

Gautham Badhrinathan


1 Answers

As 3on pointed, the correct syntax for a POST request is

request({ method:"post", url: "server.com", body:"Hello World"}, callback);

You also have a convenience method:

request.post({ url: "server.com", body:"Hello World"}, callback);

But from your question it seems like you want to stream:

var request = require('request');
var fs = require('fs');

var stream = fs.createWriteStream('file');

stream.write('Hello');
stream.write('World');

fs.createReadStream('file').pipe(request.post('http://server.com'));

Update:

  • You may break the chunks you write to the stream in any way you like, as long as you have the RAM (4mb is peanuts but keep in mind that v8 (the javascript engine behind node) has an allocation limit of 1.4GB I think);
  • You may see how much you "wrote" to the pipe with stream.bytesWritten where var stream = fs.createWriteStream('file') as you see in the piece of code above. I think you can't however know how much the other end of the pipe got, but bitesWritten should give you a pretty decent approximation.
  • You can listen to the data and end events of both stream and request.post('http://server.com')
like image 79
João Pinto Jerónimo Avatar answered Apr 17 '26 04:04

João Pinto Jerónimo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!