好的,我必须很密集,因为在使用 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 时,它永远不会被调用。
谢谢!
最佳答案
无论来自服务器的响应状态代码如何,都会调用您的回调,因此在您的回调中,检查 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 callingresponse.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/