javascript - 使用 Node js 请求模块从 API 获取 JSON,无法访问子类别

标签 javascript json node.js api request

我有一个奇怪的问题,我可以使用 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)

最佳答案

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

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

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

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

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

关于javascript - 使用 Node js 请求模块从 API 获取 JSON,无法访问子类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37981611/

相关文章:

javascript - ECMA5(最近的 JavaScript)没有任何用于复制对象的内置函数吗?

javascript - 将 Node 路由与 Backbone 路由绑定(bind)

javascript - 在 md-select 中使用 md-virtual-repeat 不起作用?

javascript - 如何根据搜索框过滤引导卡

ios - JSONValue 不解析 JSON 响应

Javascript:基于 d3 的 recurse() 的递归深度优先搜索分层重新排序

javascript - Angular/JS/Typescript-递归访问对象中的属性

javascript - jQuery 如何调用原型(prototype)中的方法?

java - JSONObject.append 到对象 - 结果是嵌套数组?

javascript - 当 preload 设置为 false 时,Node Inspector 仅加载 www 文件