http get NodeJS how to get error status code?

2019-02-02 05:11发布

问题:

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!

回答1:

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:

var https = require('https');

https.get('https://encrypted.google.com/', function(res) {
  console.log("statusCode: ", res.statusCode); // <======= Here's the status code
  console.log("headers: ", res.headers);

  res.on('data', function(d) {
    process.stdout.write(d);
  });

}).on('error', function(e) {
  console.error(e);
});

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:

var deferred = $q.defer();

var req = https.get(options, function (response) {
    var str = '';

    if (response.statusCode < 200 || response.statusCode > 299) { // (I don't know if the 3xx responses come here, if so you'll want to handle them appropriately
        deferred.reject(/*...with appropriate information, including statusCode if you like...*/);
    }
    else {
        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(/*...with appropriate information, but status code is irrelevant [there isn't one]...*/);
});


回答2:

A 400 response is not considered an error by node.js.

Try response.statusCode in this: request.on('response', function (response) {});



回答3:

Here's a very small example how to get the error code. Just change the https to http and create an error:

var https = require('https')
var username = "monajalal3"
var request = https.get("https://teamtreehouse.com/" + username +".json", function (response) {
    console.log(response.statusCode);
});

request.on("error", function (error) {
    console.error(error.status);
});