AbdulAzeez Olanrewaju
AbdulAzeez Olanrewaju

Reputation: 1078

Vite-- Cannot fetch API from a particular Address

I created A vite-react app, in my App I'm trying to fetch a public API

https://api.football-data.org/v4/matches

// This does not work

But I get

Access to fetch at 'https://api.football-data.org/v4/matches' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I know what the error means, but this is a public API and I'm confused about where to add CORS.

But I noticed I could fetch another public API successfully using the same method.

http://swapi.dev/api/planets/1/

// This API works

page.tsx

const fetchAllCompetitions = async () => {
  const res = await fetch("https://api.football-data.org/v4/matches");
  return res.json();
};

 const { data } = useQuery("users", fetchAllCompetitions);

  console.log(data);

Kinda confused.

is there anything I would have to set on the vite-config file?

Upvotes: 1

Views: 4296

Answers (1)

robertklep
robertklep

Reputation: 203429

This isn't a Vite issue, the football-data.org API simply doesn't allow for cross-domain browser requests (and the swapi.dev API does). It doesn't matter if an API is public or not.

To solve this, you need a backend-based solution that will query the API.

Upvotes: 5

Related Questions