向测验发出提取请求时出错 api
Error while making fetch request to quiz api
我在发出提取请求时遇到错误,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);
});
您收到 HTML 响应(可能是 401 错误)。根据 API docs,您需要将身份验证令牌作为 apiKey
查询参数或 X-Api-Key
header.
传递
curl
中的 -G
标志使其成为 GET 请求并将任何数据参数 (-d
) 传递到查询字符串中。这就是你出错的地方。
您正在通过 fetch()
发出 POST 请求,并试图在请求 body 中发送凭据。那是行不通的。
试试这个,发出 GET 请求并在 header
中传递凭据
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}`)
我在发出提取请求时遇到错误,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);
});
您收到 HTML 响应(可能是 401 错误)。根据 API docs,您需要将身份验证令牌作为 apiKey
查询参数或 X-Api-Key
header.
curl
中的 -G
标志使其成为 GET 请求并将任何数据参数 (-d
) 传递到查询字符串中。这就是你出错的地方。
您正在通过 fetch()
发出 POST 请求,并试图在请求 body 中发送凭据。那是行不通的。
试试这个,发出 GET 请求并在 header
中传递凭据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}`)