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

好吧,我必须是密集的,因为我无法find任何地方如何获得错误状态代码时使用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等)。 我得到的是一个半无用的错误对象,它不给我代码或任何对响应对象的引用。 我已经尝试拦截在函数(响应)callback,但是当有一个404,它永远不会被调用。

谢谢!

无论服务器的响应状态码如何,您的callback都会被调用,所以在您的callback中,请检查response.statusCode 。 也就是说,4xx状态码在你所在的层面上并不是一个错误 ; 服务器响应,只是服务器回应说资源不可用(等)

这是在文件中,但特点模糊。 下面是他们给出的例子,并且指出了相关的一点:

 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]...*/); }); 

400响应不被认为是node.js的错误。

尝试response.statusCode在这个:request.on('response',function(response){});

这是一个非常小的例子,如何获取错误代码。 只需将https更改为http并创build一个错误:

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