首页 > 解决方案 > 向测验 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);
        });

标签: javascriptapicurlfetch

解决方案


您收到 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}`)

推荐阅读