[英]Problem regarding the node-fetch api. Specifically, when attempting to use fetch to retrieve JSON data
[英]Mailchimp API returning a large gzip object when using node-fetch rather than json
我正在嘗試從mailchimp API返回已更改成員的列表,如果我使用curl / Postman,它將返回以下(正確)json:
{
"members": [
{
"id": "187fhdy650b10e8d43552b6c3672368212",
"email_address": "example@email.co.uk",
"unique_email_id": "2edbhgy73836",
"email_type": "html",
"status": "unsubscribed",
"merge_fields": {
"FNAME": "",
"LNAME": "",
"MMERGE5": "",
//etc....
我想使用Node應用程序返回此對象,因此按如下方式使用node-fetch
:
fetch(`https://us5.api.mailchimp.com/3.0/lists/<listid>/members?since_last_changed=2016-10-18T23:10:18+00:00`, {headers: authHeader})
.then((response) => {
if (response.ok) {
res.status(response.status).send(response)
} else {
res.status(response.status).send(response)
}
}).catch((error) => {
res.status(500).send(error.message)
})})
這將返回一個完全不同的json結構,對我來說,這表明它是在接收數據的過程中,並且獲取承諾不應解決。 它非常大,因此我將我認為是關鍵的信息包括在內:
{
"_opts": {},
"_chunkSize": 16384,
"_readableState": {
"objectMode": false,
"highWaterMark": 16384,
"buffer": [],
"length": 0,
"pipes": null,
"pipesCount": 0,
"flowing": null,
"ended": false,
"endEmitted": false,
"reading": false,
"sync": false,
"needReadable": true,
"emittedReadable": false,
"readableListening": false,
"resumeScheduled": false,
"defaultEncoding": "utf8",
"ranOut": false,
"awaitDrain": 0,
"readingMore": false,
"decoder": null,
"encoding": null
},
"readable": true,
"domain": null,
"_events": {
"end": [
null,
null
]
},
"_eventsCount": 7,
"_writableState": {
"objectMode": false,
"highWaterMark": 16384,
"needDrain": false,
"ending": true,
"ended": true,
"finished": false,
"decodeStrings": true,
"defaultEncoding": "utf8",
"length": 2674,
"writing": true,
"corked": 0,
"sync": false,
"bufferProcessing": false,
"writelen": 2674,
"bufferedRequest": null,
"lastBufferedRequest": null,
"pendingcb": 1,
"prefinished": false,
"errorEmitted": false,
"bufferedRequestCount": 0,
"corkedRequestsFree": {
"next": null,
"entry": null
}
},
"writable": false,
"allowHalfOpen": true,
"_transformState": {
"needTransform": false,
"transforming": true,
"writechunk": {
"type": "Buffer",
"data": [
31,
139,
8,
0,
0,
0,
0,
0,
198,....
我嘗試以不同的方式解析此內容,例如先閱讀響應:
.then((response) => {
response.text()})
.then((response) => {
res.status(200).send(response)
})
它返回一個未定義的對象。 並解析為json:
.then((response) => {
res.status(200).send(response.json())
})
它返回一個空對象{}
我還有什么可以嘗試使用提取呼叫的功能嗎?
fetch()
返回一個可解析為響應對象的promise,該對象又具有多種方法( .text()
.json()
),這些方法返回可解析為響應主體的promise。
所以試試這個:
fetch(`https://us5.api.mailchimp.com/3.0/lists/<listid>/members?since_last_changed=2016-10-18T23:10:18+00:00`, {headers: authHeader})
.then(response => {
res.status(response.status);
return response.json();
}).then(body => {
res.send(body);
}).catch(error => {
res.status(500).send(error.message)
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.