http statusCode 有时未定义 [英] http statusCode sometimes undefined

查看:31
本文介绍了http statusCode 有时未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 node.js(express) 应用程序中使用请求模块.有时会出现这个statusCode相关的错误:

I'm using request module in my node.js(express) application. Sometimes this statusCode related error occurs:

TypeError: Cannot read property
'statusCode' of undefined at Request._callback

这是我的全部代码:

request("https://www.googleapis.com/youtube/v3/search?part=snippet&q=" + docs[0].title + "&type=video&key=(some-key-variable)", {
                json: true
              }, function(error, response, resultData) {
                var yArr = [];
                if (!error || response.statusCode == 200) {
                  for (var i = 0; i < config.youtubeVideoCount; i++) {
                    var vArr = resultData.items[i];
                    yArr.push(vArr);
                  }
                } else {
                  console.log("can't find video");
                }
              });

response.statusCode 有时会出错.如何控制请求是否成功?它是请求模块中的错误吗?为什么有时状态码未定义?我认为 statusCode 应该每次都可用.

response.statusCode gives an error sometimes. How can I control that the request is successful? Is it bug in the request module? Why is statusCode undefined sometimes? I think statusCode should be available every time.

回答可能是响应超时问题,您应该执行这样的 if 语句;

Answer Probably it is response timeout issue and u should do an if statement like this;

if (response === undefined || response.statusCode != 200){ console.log("there is a prob"); }

这段代码首先控制 response 变量,然后是 response.statuscode ,所以如果 response undefined 不控制 response.statusCode 因此,我们不会得到任何错误.

this code firstly control response variable and then response.statuscode , so if response undefined don't control response.statusCode thus , we can't get any error.

推荐答案

这是一种解决方法,因为 responseundefined 的原因可能有多种:

This is a workaround, as there might be several reasons why response is undefined:

if (!error && response.statusCode == 200) {
    // do your stuff here..
}

这篇关于http statusCode 有时未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆