簡體   English   中英

使用Node js請求模塊從API獲取JSON,無法訪問子類別

[英]Using Node js request module for JSON from API, can't access subcategories

我有一個奇怪的問題,我可以使用Node js和request模塊從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);
})

標頭是響應參數的屬性,用於從請求中獲取響應標頭(諸如內容類型,cookie之類的數據)

這里的問題是您閱讀響應的方式。 在您的情況下, body是數組。 因此您應該像body[index].categoryIDbody[index].category一樣閱讀它,其中index可以在05之間,因為您的響應有6對象

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM