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:
Note that in the example
req.end()was called. Withhttp.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