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.
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.
2 Answers
Reset to default 14Elaborating on jeremy's answer, here is an example of checking the status code that works for me:
http.get(url, function (res) {
if (res.statusCode != 200) {
console.log("non-200 response status code:", res.statusCode);
console.log("for url:", url);
return;
}
// do something great :-)
});
response.statusCode contains the status code, you can get that in the http.get(...,cb()) or you can set up a listener
request.on('response', function (response) {});
that can get the status code. You can then destroy the request if you want to cancel the GET, or handle it however you want.