mlgtour
mlgtour

Reputation: 1

API Error code Nodejs

var API_KEY= 'XXX';
CHANNEL_ID = 'XXX';
router.get('/', function(req, res) {
request.get('https://www.googleapis.com/youtube/v3/search', { part: 'snippet', channelId: CHANNEL_ID, type: 'video', eventType: 'live', key: API_KEY }, function(data) {
    try {
        if(data['items'].length > 0) 
    res.json({status: true});
    }
      catch (err) {
          res.json({status: false});
          console.log(err)
        }
    });
});

TypeError: Cannot read property 'length' of undefined
    at Request._callback (C:\Users\Steve\Desktop\Own api check\server.js:24:21)
    at self.callback (C:\Users\Steve\Desktop\Own api     check\node_modules\request\request.js:185:22)
    at Request.emit (events.js:182:13)
    at Request.start (C:\Users\Steve\Desktop\Own api     check\node_modules\request\request.js:749:10)
    at Request.end (C:\Users\Steve\Desktop\Own api     check\node_modules\request\request.js:1506:10)
    at end (C:\Users\Steve\Desktop\Own api check\node_modules\request\request.js:560:14)
at Immediate._onImmediate (C:\Users\Steve\Desktop\Own api check\node_modules\request\request.js:574:7)
    at runCallback (timers.js:696:18)
at tryOnImmediate (timers.js:667:5)
at processImmediate (timers.js:649:5)

Full code :

Upvotes: 0

Views: 731

Answers (1)

RedJandal
RedJandal

Reputation: 1213

The error is on this line

if(data['items'].length > 0) 

The data object does not have a property of 'items'. Do a console.log of the data object to see what is returned. It looks like the Youtube API is not called correctly and returning an error instead.

Try the following code in your request instead:

request({url: "https://www.googleapis.com/youtube/v3/search?",
         qs:{ 
              part: 'snippet', 
              channelId: CHANNEL_ID, 
              type: 'video', 
              eventType: 'live', 
              key: API_KEY
            }
}, function(err, response, data){
    if (err){
      console.log(err);
    }

    console.log(data);
    if(data['items'].length > 0) {
        res.json({status: true});
    }
});

Upvotes: 0

Related Questions