I use following http.get() call to call a local endpoint:
http.get({
host: 'localhost',
port: 80,
path: '/service/info?id=' + id
}, function(response) {
console.log(response);
response.setEncoding('utf8');
var data = "";
response.on('data', function(chunk) {
data += chunk;
});
response.on('end', function() {
if(data.length > 0) {
try {
var data_object = JSON.parse(data);
} catch(e) {
return;
}
}
});
}).on("error", function (){console.log("GET request error")});
However, if I send a malformed request, which would trigger a HTTP 400, the request is synthetically incorrect etc, even though the response.statusCode in function(response) is 400, it would end up to the catch() response.on('end', function() {} instead of emitting the error event on http.get(), I wonder why that's the case and how i can handle HTTP 400 response as an error on node.js.
If it gets to catch(e), it waits a long time till it responses anything to the client, which is also weird. I want the server to respond to the client that it hits a 400 as soon as possible.