OK, I must be dense since I cannot find anywhere how to get the error status codes when using Node.JS http.get
or http.request
.
My code:
var deferred = $q.defer();
var req = https.get(options, function(response) {
var str = '';
response.on('data', function(chunk) {
str += chunk;
});
response.on('end', function() {
console.log("[evfService] Got user info: " + str);
deferred.resolve(str);
});
});
req.on('error', function(e) {
deferred.reject(e);
});
In that "req.on" bit, what I want is the http status code (i.e. 401, 403, etc.). What I get is a semi-useless error object that does not give me the code or any reference to the response object.
I have tried intercepting in the function(response) callback, but when there is a 404, it never gets called.
Thanks!
Best Answer
Your callback gets called regardless of the response status code from the server, so within your callback, check
response.statusCode
. That is, a 4xx status code isn't an error at the level you're working at; the server responded, it's just that the server responded by saying the resource wasn't available (etc.)This is in the documentation but characteristically vague. Here's the example they give, with a comment pointing to the relevant bit:
If you try that with (say) an unknown resource, you'll see
statusCode: 404
.So for what you're doing, you may want something like this:
¹ The empty
data
event handler in the branch handling non-OK status codes is there because of this note in the documentation:Since we're passing a function to
https.get
, we're hooking the'response'
event, which suggests we need to do one of those things (in this case, I've added a do-nothingdata
handler). Thanks to Nicolas2bert for pointing that out!.