我创建了一个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 workspage.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文件上有什么需要设置的吗?
发布于 2022-05-26 08:07:50
这不是一个Vite问题,football-data.org API根本不允许跨域浏览器请求(而swapi.dev API允许)。API是否公开并不重要。
要解决这个问题,您需要一个基于后端的解决方案来查询API。
https://stackoverflow.com/questions/72387344
复制相似问题