javascript - 向测验 api 发出获取请求时出错
问题描述
我在发出 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);
});
解决方案
您收到 HTML 响应(可能是 401 错误)。根据API 文档,您需要将身份验证令牌作为apiKey
查询参数或X-Api-Key
标头传递。
中的-G
标志curl
使其成为 GET 请求并将任何数据参数 ( -d
) 传递到查询字符串中。那就是你出错的地方。
您正在通过 POST 请求fetch()
并尝试在请求正文中发送凭据。那是行不通的。
试试这个,发出 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}`)
推荐阅读
- javascript - Angular - 检测背景图像何时加载
- angular - 分别在列中搜索(Angular 7)
- php - 使用php从mysql获取数据不返回结果
- php - 表单未在 codeigniter 2.0 中上传文件
- python - 匿名函数/闭包问题
- javascript - Laravel 错误 405(不允许方法)Ajax 发布
- java - 具有非纯函数链的 Java Stream API
- google-sheets - 如何在谷歌表格的查询中动态增加或减少限制值
- azure-devops-rest-api - Azure DevOps REST:从构建中检索所有警告消息
- android - Android 小部件未显示其属性