我有一個GET請求中下面的代碼中的NodeJSNodeJS獲取請求。無法訪問JSON元素
response.on('data', function (chunk) {
console.log(chunk);
JSON.parse(chunk);
console.log("ch"+chunk.product.productId);
responseData+=chunk;
});
第一的console.log打印整個響應,這是一個字符串形式的JSON:
{"product":[{"defaultProductUrl":"http:\/\/www.zappos.com\/product\/7306789","defaultImageUrl":"http:\/\/www.zappos.com\/images\/z\/2\/1\/3\/2\/5\/4\/2132548-p-DETAILED.jpg","productId":"7306789","productName":"Pro Short","brandId":"1630","brandName":"CW-X"}],"statusCode":"200"}
第二個卻拋出一個錯誤:
console.log("ch"+chunk.product.productId);
TypeError: Cannot read property 'productId' of undefined
at IncomingMessage.<anonymous> (c:\Users\Udai\Desktop\Zappos\server.js:78:38)
at IncomingMessage.EventEmitter.emit (events.js:95:17)
at IncomingMessage.<anonymous> (_stream_readable.js:746:14)
at IncomingMessage.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:408:10)
at emitReadable (_stream_readable.js:404:5)
at readableAddChunk (_stream_readable.js:165:9)
at IncomingMessage.Readable.push (_stream_readable.js:127:10)
at HTTPParser.parserOnBody [as onBody] (http.js:141:22)
at Socket.socketOnData [as ondata] (http.js:1584:20)
上這是怎麼回事任何想法?
工作就像一個魅力。 –