我创建了一个vite-react应用程序,在我的应用程序中,我试图获取一个公共API
https://api.football-data.org/v4/matches
// This does not work
但是我得到
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.
我知道错误是什么意思,但这是一个公共API,我很困惑在哪里添加CORS。
但是我注意到我可以使用相同的方法成功地获取另一个公共API。
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);
有点困惑。
我需要在vite-config
文件上设置什么吗?
这不是一个Vite问题,football-data.org
API根本不允许跨域浏览器请求(和swapi.dev
API)。API是否公开并不重要。
为了解决这个问题,你需要一个基于后端的解决方案来查询API。