在发出fetch请求时,我得到了一个错误,curl命令运行良好,这是
curl https://quizapi.io/api/v1/questions -G \
-d apiKey=my_key但是当我做javascript请求时
fetch("https://quizapi.io/api/v1/questions", {
body: "apiKey=my_key",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: "POST"
})
.then((res) => res.json())
.then((data) => {
console.log(data);
});我犯了个错误
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0编辑
fetch('https://quizapi.io/api/v1/questions', {
headers: {
'X-Api-Key': `${apiKey}`,
},
})
.then((res) => res.json())
.then((data) => {
console.log(data);
});发布于 2021-09-08 07:26:33
您将得到一个HTML响应(可能是401错误)。根据API文档,您需要将身份验证令牌作为apiKey查询参数或X-Api-Key头传递。
-G标志在curl中使它成为一个GET请求,并将任何数据参数(-d)传递给查询字符串。那就是你要出错的地方。
您正在通过fetch()发出一个POST请求,并试图在请求正文中发送凭据。那是行不通的。
尝试这样做,发出GET请求并在标头中传递凭据。
fetch("https://quizapi.io/api/v1/questions", {
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://stackoverflow.com/questions/69098544
复制相似问题