Enterprise Framework

Software Solutions in the Enterprise

Node.js - HTTP with Error, Done, Data, End, Timeout example


var https = require('https');
var querystring = require('querystring');
var postData = { data : "something" };
var options = {
hostname: 'www.yourdomain.com',
path: '/api/book',
method: 'POST',
headers: {
"Content-Type": "application/json",
"Content-Length": postData.length
}
};

var req = https.request(options, function (res) {
res.setEncoding('utf8');

res.on('data', function (chunk) {
console.log("[RESPONSE DATA]", chunk);
});

res.on('end', function (data) {

if (res.statusCode >= 200 && res.statusCode < 300) {
console.log("[SUCCESS]");
} else {
console.log("[HTTP RESPONSE STATUS CODE ERROR]", res.statusCode);
console.log("[HTTP RESPONSE STATUS MESSAGE ERROR]", res.statusMessage);
}
});
});
req.setNoDelay(true);
req.setTimeout(28000, function(e) {
console.log("Timeout Fired at 29000 ms");
});

req.on('error', function (e) {
console.log("[FORWARD ERROR]", e);

if (e.statusCode === "ECONNRESET") {
console.log("Timeout received");
}
});

req.write(postData);
req.end();

Comments are closed