Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is the request fired? http.request()

Tags:

node.js

A little question concerning node's http.request(options, callback) method.
I got the following example code from the docs:

var options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

Question: When is the actual HTTP request getting fired?

Is it at the time of assigning the request to the req variable (line 8), or maybe at req.end()?

like image 952
bijan Avatar asked May 11 '26 03:05

bijan


1 Answers

The explanation is right in the documentation following the example:

Note that in the example req.end() was called. With http.request() one must always call req.end() to signify that you're done with the request - even if there is no data being written to the request body.

The call of req.end() is mandatory. Note that req is a http.ClientRequest. The documentation of http.ClientRequest.prototype.end gives you the final clue:

request.end([data], [encoding])
Finishes sending the request

like image 51
Zeta Avatar answered May 13 '26 17:05

Zeta



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!