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

时间:2014-05-17 14:23:17

标签: javascript node.js http

好吧,我必须密集,因为在使用Node.JS http.get或http.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时,它永远不会被调用。

谢谢!

3 个答案:

答案 0 :(得分:39)

无论来自服务器的响应状态代码如何,都会调用您的回调,因此在回调中,请检查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
        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]...*/);
});

答案 1 :(得分:8)

node.js不会将错误代码400响应视为错误。

在此尝试response.statusCode

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

答案 2 :(得分:5)

以下是如何获取错误代码的一个非常小的示例。只需将$(".item").click(function() { $(this).parent('li').addClass('active'); }); 更改为https并创建错误:

http