賞金將在 7 小時后到期。此問題的答案有資格獲得 100聲望賞金。 Aaronv想提請更多關注這個問題:
我很忙,真的需要你的幫助
我正在向 crypto.com 公共 API(參考)發送 POST 請求node-fetch。更具體地說,我正在嘗試呼叫私有方法get-account-summary并且我正在使用我的 API 密鑰和我的密鑰在他們的 API 參考頁面上預先簽署請求(請參閱數字簽名)。
const requestBody = JSON.stringify(signRequest(request, apiKey, apiSecret));
fetch('https://api.crypto.com/v2/private/get-account-summary', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: requestBody
})
.then(response => response.body)
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
該請求顯然是成功的,但我正在努力理解應該看起來像這樣的 API 回應:
{
"id": 11,
"method": "private/get-account-summary",
"code": 0,
"result": {
"accounts": [
{
"balance": 99999999.905000000000000000,
"available": 99999996.905000000000000000,
"order": 3.000000000000000000,
"stake": 0,
"currency": "CRO"
}
]
}
}
但這是我實際得到的:
Success: PassThrough {
_readableState: ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: [],
flowing: null,
ended: true,
endEmitted: false,
reading: false,
constructed: true,
sync: false,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
errorEmitted: false,
emitClose: true,
autoDestroy: true,
destroyed: false,
errored: null,
closed: false,
closeEmitted: false,
defaultEncoding: 'utf8',
awaitDrainWriters: null,
multiAwaitDrain: false,
readingMore: false,
dataEmitted: false,
decoder: null,
encoding: null,
[Symbol(kPaused)]: null
},
_events: [Object: null prototype] {
prefinish: [Function: prefinish],
error: [Function (anonymous)]
},
_eventsCount: 2,
_maxListeners: undefined,
_writableState: WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: true,
needDrain: false,
ending: true,
ended: true,
finished: true,
destroyed: false,
decodeStrings: true,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: false,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
afterWriteTickInfo: null,
buffered: [],
bufferedIndex: 0,
allBuffers: true,
allNoop: true,
pendingcb: 0,
constructed: true,
prefinished: true,
errorEmitted: false,
emitClose: true,
autoDestroy: true,
errored: null,
closed: false,
closeEmitted: false,
[Symbol(kOnFinished)]: []
},
allowHalfOpen: true,
[Symbol(kCapture)]: false,
[Symbol(kCallback)]: null
}
您可能已經注意到我將 記錄response.body到控制臺而不是response.json()因為每當我呼叫后者時,我都會收到“無效的 json 錯誤”
Error: FetchError: invalid json response body at https://api.crypto.com/v2/private/get-account-summary reason: Unexpected end of JSON input at C:\Users\...\app\node_modules\node-fetch\lib\index.js:273:32 at processTicksAndRejections (node:internal/process/task_queues:96:5) { type: 'invalid-json'
uj5u.com熱心網友回復:
許多 API 堆疊根據 2 個 Promise 作業:
- 發出遠程請求
- 反序列化回應
根據檔案,您需要等待.json()電話。
import fetch from 'node-fetch';
const response = await fetch('https://httpbin.org/post', {
method: 'post',
body: JSON.stringify(body),
headers: {'Content-Type': 'application/json'}
});
const data = await response.json();
嵌套的 Promise 在使用時看起來更混亂then,這就是為什么很多人更喜歡 async await 語法的原因,但這會起作用:
request('https://api.crypto.com/v2/private/get-account-summary', {
json: true,
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: requestBody
})
.then(response => {
response.json()
.then(data => {
console.log(data);
})
})
uj5u.com熱心網友回復:
Fetch 回傳一個回應流。更簡單的方法是使用 npmrequest包。
前任 :
const request = require('request');
const requestBody = JSON.stringify(signRequest(request, apiKey, apiSecret));
request('https://api.crypto.com/v2/private/get-account-summary', {
json: true,
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: requestBody
})
.then(response => response.body)
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
uj5u.com熱心網友回復:
編輯:對不起,我錯過了問題的結尾。如果json()無效并且text()沒有回傳任何內容,我會說您應該檢查您的請求正文。請求成功,但您得到一個空回應。
不知道你為什么使用response.body. json()如果您想要 JSON 格式的回應,則需要使用。這將獲取正文并回傳一個決議為請求格式的承諾。你可以在這里閱讀。
因此,您的代碼應如下所示:
fetch('https://api.crypto.com/v2/private/get-account-summary', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: requestBody
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/428070.html
標籤:javascript 节点.js json api
