http statusCode 有时未定义

http statusCode sometimes undefined

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

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 有时是未定义的?我觉得statusCode应该每次都可用。

回答 可能是响应超时问题,你应该像这样做一个 if 语句;

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

这段代码先控制response变量再控制response.statuscode,所以如果response undefined不控制response.statusCode,就不会报错。

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

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