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()?
The explanation is right in the documentation following the example:
The call of
req.end()is mandatory. Note thatreqis ahttp.ClientRequest. The documentation ofhttp.ClientRequest.prototype.endgives you the final clue: