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