Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

http statusCode sometimes undefined

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

This is my whole code:

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 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.

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

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.

like image 555
Erdi Avatar asked Apr 20 '15 15:04

Erdi


1 Answers

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

if (!error && response.statusCode == 200) {
    // do your stuff here..
}
like image 54
Nikos M. Avatar answered Nov 13 '22 07:11

Nikos M.