无法解决No 'Access-Control-Allow-Origin' in React App(我只有前端)

Can't solve No 'Access-Control-Allow-Origin' in React App(I have only front-end)

使用 Rapidapi API 并尝试从此端点获取动态数据 https://www.freetogame.com/api/game?id=${number} 最后出现 CORS 错误。

更新: 我使用了错误的 API(https://www.freetogame.com/api/game?id=${number}) I was supposed to use https://free-to-play-games-database.p.rapidapi.com/api/game 这个 API 并且它修复了我的 CORS 错误(实际上我没有安装任何库或依赖项或者没有添加代理)。谢谢一切为了你的支持!

错误 Access to fetch at 'https://www.freetogame.com/api/game?id=1' 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.

我已经尝试(安装)CORS 扩展运行良好,如果关闭扩展出现错误(您可以在上面看到)并尝试了最推荐的选项添加 packeges.json 文件 "proxy": "https://www.freetogame.com/", 基础url还是无法解决问题

仅供参考:我没有后端代码或没有使用 express

import { Container, Grid, Box } from "@mui/material";
import { useState, useEffect } from "react";
import { useParams } from "react-router-dom";

import Header from "../Header/Header";
import Footer from "../Footer/Footer";
import GameListInfoLeft from "./GameListInfoLeft";
import GameListInfoRight from "./GameListInfoRight";

const GameListInfo = () => {
  let { id } = useParams();
  const [gameInfo, setGameInfo] = useState([]);

  const getInfo = async (name) => {
    const data = await fetch(`https://www.freetogame.com/api/game?id=${name}`);
    const response = await data.json();
    setGameInfo(response);
  };

  useEffect(() => {
    getInfo(id);
  }, [id]);

  return (
    <>
      <Header />
      <Container>
        <Box sx={{ padding: 4, backgroundColor: "#2A2E33", color: "#AAAAAA" }}>
          <Grid container spacing={1}>
            <Grid item xs={12} sm={5}>
              <GameListInfoLeft gameInfoLeft={gameInfo} />
            </Grid>
            <Grid item xs={12} sm={7}>
              <GameListInfoRight gameInfoRight={gameInfo} />
            </Grid>
          </Grid>
        </Box>
      </Container>
      <Footer />
    </>
  );
};

export default GameListInfo;

其实你目前没有使用Rapidapi,你直接使用FreeToGameAPI,如果你使用Rapidapi,问题就解决了。

主机应该是:free-to-play-games-database.p.rapidapi.com 和所有 RapidApi API 一样,您需要包含 RapidAPI 键。

类似于下面的示例:

const options = {
    method: 'GET',
    headers: {
        'X-RapidAPI-Host': 'free-to-play-games-database.p.rapidapi.com',
        'X-RapidAPI-Key': 'SIGN-UP-FOR-KEY'
    }
};

fetch('https://free-to-play-games-database.p.rapidapi.com/api/game?id=452', options)
    .then(response => response.json())
    .then(response => console.log(response))
    .catch(err => console.error(err));