0

我的 node.js 应用程序中有以下请求调用

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

而且,我正在TypeError: Cannot read property 'items' of undefined 处理响应。

我正在尝试使用的 JSON 对象是

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

为什么说items是未定义的?

而且我还想知道我是否想在这个请求包装器中执行该函数,我需要像我一样将它包装在括号内吗?我确实得到了没有括号的语法错误。

4

1 回答 1

3

您的代码存在一些问题:

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

您在没有参数的情况下调用匿名函数。body因此undefined在函数内部。您应该省略IIFE - 它在这里对您没有帮助。

Object.keys(body.items)

Object.keys返回对象的属性名称数组。body.items是一个数组,所以你不需要使用它——你应该直接迭代对象。

pid = item.contentDetails.relatedPlaylists.uploads

contentDetails是一个数组。如果您打算使用第一个元素,您的代码应为:item.contentDetails[0].relatedPlaylists.uploads

进行这些更改后,您将获得:

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);
  })
})
于 2015-10-25T21:55:18.040 回答