[Node.js] http.request with [Error: socket hang up] code: 'ECONNRESET'
I encountered an [Error: socket hang up] code: ‘ECONNRESET’ error in Node.js code that generates HTTPS requests.
Error Message
Error: socket hang up
at createHangUpError (http.js:1124:15)
at Socket.socketOnEnd [as onend] (http.js:1272:23)
at TCP.onread (net.js:389:26)
The cause was that I was using the http module instead of the https module to send HTTPS requests…
So, you can fix it by properly using the https module as shown below.
var https = require('https');
/**
* HTTPS POST (JSON)
*
* @param {Object} jsonData
* @param {Function} callback
* @param {String} encoding
*/
function httpJsonPost(jsonData, callback, encoding) {
jsonData = jsonData || {};
encoding = encoding || 'utf8';
var jsonDataString = JSON.stringify(jsonData);
var headers = {
'Content-Type': 'application/json',
'Content-Length': jsonDataString.length
};
var options = {
host: 'api.example.com',
port: 443,
path: '/1/push',
method: 'POST',
headers : headers
};
var req = https.request(options, function(res) {
res.setEncoding(encoding);
var responseString = '';
res.on('data', function(chunk) {
responseString += chunk;
});
res.on('end', function() {
var resultObject = JSON.parse(responseString);
return callback(null, resultObject, res.statusCode, JSON.stringify(res.headers));
});
});
req.on('error', function(e) {
return callback(e);
});
req.write(jsonDataString);
req.end();
}
[Reference Information]
・HTTPS Node.js v0.11.2 Manual & Documentation
That’s all from the Gemba.