【问题标题】:Using Node js request module for JSON from API, can't access subcategories使用来自 API 的 JSON 的 Node js 请求模块,无法访问子类别
【发布时间】:2016-06-23 03:01:07
【问题描述】:

我有一个奇怪的问题,我可以使用 Node js 和请求模块从 API 源成功获取数据,但是当我尝试访问 JSON 数据的某个子类别时,该对象变得未定义。

这是我的代码:

var request = require("request")

var url = "http://api.8coupons.com/v1/getcategory"

request({
    url: url,
    json: true
}, function (error, response, body) {

    if (!error && response.statusCode === 200) {
        console.log(body) // Print the json response
        console.log(body.headers['categoryID']) // creates an error
        console.log(body.categoryID) // creates an error
    }
})

这是我运行程序时的终端输出:

node getJS.js 
[ { categoryID: '1', category: 'Restaurants' },   
{categoryID: '2', category: 'Entertainment' },   
{ categoryID: '3', category: 'Beauty & Spa' },   
{ categoryID: '4', category: 'Services' },  
{ categoryID: '6', category: 'Shopping' },   
{ categoryID: '7', category: 'Travel' } ]

C:\path\to\code\getJS.js:12
    >         console.log(body.headers['categoryID'])
    >                                 ^
    > 
    > TypeError: Cannot read property 'categoryID' of undefined
    >     at Request._callback (C:\Users\Jay\Desktop\Bill-e\getJS.js:12:33)
    >     at Request.self.callback (C:\Users\Jay\Desktop\Bill-e\node_modules\request\request.js:200:22)
    >     at emitTwo (events.js:87:13)
    >     at Request.emit (events.js:172:7)
    >     at Request.<anonymous> (C:\Users\Jay\Desktop\Bill-e\node_modules\request\request.js:1067:10)
    >     at emitOne (events.js:82:20)
    >     at Request.emit (events.js:169:7)
    >     at IncomingMessage.<anonymous> (C:\Users\Jay\Desktop\Bill-e\node_modules\request\request.js:988:12)
    >     at emitNone (events.js:72:20)
    >     at IncomingMessage.emit (events.js:166:7)

【问题讨论】:

    标签: javascript json node.js api request


    【解决方案1】:

    我认为你这里有一个小错误。

    您在第一级的 json 数据是一个数组,因此,要访问数据,您需要传递要从数组中获取的索引(直接或在迭代中)

    console.log(body[0].categoryID);
    

    body.forEach(function(item) {
        console.log(item.categoryID);
    })
    

    headers 是响应参数的一个属性,用于从请求中获取响应头(内容类型、cookie 等数据)

    【讨论】:

    • 就是这样!谢谢!!
    【解决方案2】:

    这里的问题是您阅读响应的方式。在您的情况下,body 是数组。所以你应该像body[index].categoryIDbody[index].category一样阅读它,其中index可以在05之间,因为你的回复有6对象

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-08
      • 1970-01-01
      • 2017-12-17
      相关资源
      最近更新 更多