首页 > 解决方案 > 如何从 react 应用程序中获取 swapi?

问题描述

我正在尝试使用以下代码从反应应用程序调用Star Wars Api (swapi) :

export function getAsync(route: string, baseUrl: string) {
  // var url = baseUrl + "/" + route;
  let url = "http://swapi.dev/api/planets?page=1";
  let status: number;

  return fetch(url, {
    headers: {
      "content-type": "application/json",
    },
  })
    .then((response: any) => {
      status = response.status;
      console.log(response);
      return response.json();
    })
   //more stuff
}

但是我收到此错误:

Access to fetch at 'http://swapi.dev/api/planets?page=1' from origin 'http://localhost:3000' has been 
blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not 
allowed for a preflight request.

我需要做什么来修改我的获取请求?我注意到连接到此 API 的示例使用了 swapi.co,但后来改为 swapi.dev。

标签: reactjsfetch

解决方案


当请求本身满足一定的一组要求时,浏览器认为该请求是一个“简单”请求:

使用 Content-Type 标头时,仅允许以下值:application/x-www-form-urlencoded、multipart/form-data 或 text/plain

资源

所以我不能用"content-type": "application/json"。实际上,我认为当您将数据从客户端发送到服务器时,应该使用内容类型。对于简单的 GET 请求,我们通常不会这样做。

所以我应该写:

 return fetch(url, {
  })

推荐阅读