0

I have the following request call in my node.js app

   request({ url:chanURL, qs:chanProperties}, function(err, response, body) {
      if(err) { console.log(err); return; }
      body = JSON.parse(body);

      (function (body) {
        Object.keys(body.items).forEach(function(item) {
            pid = item.contentDetails.relatedPlaylists.uploads;
            console.log(pid);
        })
      })();
    })

And, I'm getting TypeError: Cannot read property 'items' of undefined while processing the response.

The JSON object that I'm trying to work with is

{ kind: 'youtube#channelListResponse',
  etag: '"0KG1mRN7bm3nResDPKHQZpg5-do/B7stMlWJTBpmW2q34yWKIzz8fF8"',
  pageInfo: { totalResults: 1, resultsPerPage: 1 },
  items: 
   [ { kind: 'youtube#channel',
       etag: '"0KG1mRN7bm3nResDPKHQZpg5-do/vV2FFZUI5inz53NuQDJMTs3tdQk"',
       id: 'UCwy6X3JB24VTsDFqMwdO5Jg',
       contentDetails: [Object] } ] }

Why does it say items is undefined?

And I also would like to know if I want to execute the function within this request wrapper, I need to wrap it inside the parenthesis like I did? I did get syntax error without the parenthesis.

1 Answer 1

3

There are a few problems with your code:

(function (body) { /* ... */ })()

You're calling the anonymous function without an argument. body is therefore undefined inside the function. You should omit the IIFE - it doesn't help you here.

Object.keys(body.items)

Object.keys returns an array of the property names for an Object. body.items is an Array, so you don't need to use it - you should iterate over the object directly.

pid = item.contentDetails.relatedPlaylists.uploads

contentDetails is an Array. If you mean to use the first element, your code should read: item.contentDetails[0].relatedPlaylists.uploads

Making those changes leaves you with:

request({ url:chanURL, qs:chanProperties}, function(err, response, body) {
  if(err) { console.log(err); return; }
  body = JSON.parse(body);

  body.items.forEach(function(item) {
      pid = item.contentDetails[0].relatedPlaylists.uploads;
      console.log(pid);
  })
})
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your insightful answer, this is really helpful. Would you mind adding how I can structure so I can call another another request call in a chain or using callback? Now I got the playlist ID of my Youtube, I need to make another similar request to get the list of videos using this playlist ID. I know how to get the videos but I'm not sure how to put these two requests together to ultimately get the video data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.