简体   繁体   English

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

[英]http get NodeJS how to get error status code?

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 .好的,我必须很密集,因为在使用 Node.JS http.gethttp.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 (ie 401, 403, etc.).在那个“req.on”位中,我想要的是 http 状态代码(即 401、403 等)。 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.我尝试在函数(响应)回调中进行拦截,但是当有 404 时,它永远不会被调用。

Thanks!谢谢!

Your callback gets called regardless of the response status code from the server, so within your callback, check response.statusCode .无论来自服务器的响应状态代码如何,您的回调都会被调用,因此在您的回调中,检查response.statusCode That is, a 4xx status code isn't an error at the level you're working at;也就是说,4xx 状态代码在您工作的级别不是错误 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 .如果您尝试使用(例如)未知资源,您将看到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
        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]...*/);
});

¹ The empty data event handler in the branch handling non-OK status codes is there because of this note in the documentation: ¹ 处理非 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. ...如果添加了'response'事件处理程序,则必须使用响应对象中的数据,方法是在有'readable'事件时调用response.read()或添加'data'处理程序,或者通过调用.resume()方法。 Until the data is consumed, the 'end' event will not fire.在数据被消耗之前, 'end'事件不会触发。 Also, until the data is read it will consume memory that can eventually lead to a 'process out of memory' error.此外,在读取数据之前,它会消耗内存,最终会导致“进程内存不足”错误。

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-nothing data handler).由于我们将一个函数传递给https.get ,因此我们正在挂钩'response'事件,这表明我们需要做其中一件事情(在这种情况下,我添加了一个什么都不做的data处理程序)。 Thanks to Nicolas2bert for pointing that out!.感谢Nicolas2bert指出这一点!。

An error code 400 response is not considered an error by node.js.错误代码 400 响应不被 node.js 视为错误。

Try response.statusCode in this:在此尝试response.statusCode

request.on('response', function (response) {}); 

Here's a very small example how to get the error code.这是一个非常小的示例,如何获取错误代码。 Just change the https to http and create an error:只需将https更改为http并创建错误:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM