How do I fetch from swapi from react app?

Viewed 714

I'm trying to call the Star Wars Api (swapi) from a react app with this code:

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
}

However I get this error:

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.

What do I need to do to modify my fetch request? I notice that examples of connecting to this API used swapi.co but it's since changed to swapi.dev.

2 Answers

The browser deems the request to be a "simple" request when the request itself meets a certain set of requirements:

When using the Content-Type header, only the following values are allowed: application/x-www-form-urlencoded, multipart/form-data, or text/plain

Source

So I can't use "content-type": "application/json" . Actually I think that content-type is supposed to be used for when you are sending data up from client to server. We are generally not doing that for a simple GET request.

So I should write:

 return fetch(url, {
  })
Related