我在提出獲取請求時得到了一個錯誤,而curl命令作業正常,這就是
curl https://quizapi.io/api/v1/questions -G
-d apiKey=my_key
但是當我做一個javascript請求時
fetch("https://quizapi.io/api/v1/questions"/span>, {
body: "apiKey=my_key",
headers: {
"Content-Type": "application/x-www-form-urlencoded"。
},
method: "POST"
})
.then((res) => res.json()
.then((data) => {
console.log(資料)。
});
我得到一個錯誤
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
編輯
fetch('https://quizapi.io/api/v1/questions'/span>, {
headers: {
'X-Api-Key': `${apiKey}`。
},
})
.then((res) => res.json()
.then((data) => {
console.log(資料)。
});
uj5u.com熱心網友回復:
你得到的是一個HTML回應(可能是401錯誤)。根據API檔案,你需要將認證令牌作為apiKey查詢引數或X-Api-Key頭傳遞。
curl中的G標志使其成為一個GET請求,并將任何資料引數(-d)傳遞到查詢字串。這就是你出錯的地方。
你是在做一個 "P "的請求。
您正在通過fetch()發出一個POST請求,并試圖在請求體中發送證書。這是不可能實作的。
請嘗試這樣做,發出一個 GET 請求,并在頭中傳遞證書
。fetch("https://quizapi.io/api/v1/questions"/span>, {
headers: {
"X-API-Key": apiKey
},
//the default method is "GET"。
}).then(res => {
if (!res.ok) {
throw new Error(res)
}
return res.json()
}).then(console.log)。 catch(console.error)
另一種方法是在查詢字串中包含apiKey
const params = new URLSearchParams({ apiKey })
fetch(`https://quizapi.io/api/v1/questions?${params}`)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/319772.html
標籤:
下一篇:運行curl的python腳本
