javascript - http get NodeJS如何获取错误状态码?

标签 javascript node.js http

好的,我必须很密集,因为在使用 Node.JS http.gethttp.request 时,我无法找到任何获取错误状态代码的方法。

我的代码:

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);
});

在那个“req.on”位中,我想要的是 http 状态码(即 401、403 等)。我得到的是一个半无用的错误对象,它没有给我代码或对响应对象的任何引用。

我尝试在函数(响应)回调中进行拦截,但是当有 404 时,它永远不会被调用。

谢谢!

最佳答案

无论来自服务器的响应状态代码如何,都会调用您的回调,因此在您的回调中,检查 response.statusCode。也就是说,4xx 状态代码不是您正在工作的级别的错误;服务器响应了,只是服务器响应说资源不可用(等等)

这是in the documentation但特征模糊。这是他们给出的示例,并带有指向相关位的注释:

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);
});

如果您尝试使用(比如说)未知资源,您会看到 statusCode: 404

所以对于你正在做的事情,你可能想要这样的东西:

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
        response.on("data", function() { } ); // ¹
        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]...*/);
});

¹ 处理非 OK 状态代码的分支中的空 data 事件处理程序存在,因为文档中有此注释:

...if a 'response' event handler is added, then the data from the response object must be consumed, either by calling response.read() whenever there is a 'readable' event, or by adding a 'data' handler, or by calling the .resume() method. Until the data is consumed, the 'end' event will not fire. Also, until the data is read it will consume memory that can eventually lead to a 'process out of memory' error.

由于我们将一个函数传递给 https.get,因此我们正在 Hook 'response' 事件,这表明我们需要做其中一件事情(在这种情况下,我添加了一个无操作的 data 处理程序)。 感谢 Nicolas2bert指出这一点!。

关于javascript - http get NodeJS如何获取错误状态码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23712392/

相关文章:

javascript - res.json 不在回调函数内工作

javascript - 无法访问本地 Node 服务器上创建的API

Android Volley NetworkImageView 不适用于某些图像

javascript - 为什么 jQuery.getJSON() 会压扁我的 javascript 字典?

javascript - 选择包含特殊类的图像 - 纯 javascript

javascript - 在对象中执行函数

java - 通过 HttpGet 对象检索数据时设置超时值

Javascript 函数编程——接收复杂的参数

javascript - 如何从 socket.io 发出的回调中获取回调,然后将其返回给父函数

angularjs - 在 Node 应用程序中使用 Angular $http 服务