Usando la API de Rapidapi e intentando obtener datos dinámicos de este punto final https://www.freetogame.com/api/game?id=${number} al final obtengo el error CORS.
ACTUALIZACIÓN: Estaba usando la API incorrecta ( https://www.freetogame.com/api/game?id=${number} ) Se suponía que debía usar https://free-to-play-games-database.p .rapidapi.com/api/game esta API y corrigió mis errores CORS (literalmente, no instalé ninguna biblioteca o dependencia o no agregué proxy). ¡Gracias por todo tu apoyo!
Error 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.
Probé (instalé) la extensión CORS que funciona muy bien si desactivo la extensión y obtengo un error (puede ver arriba) y probé la opción más recomendada agregando el archivo "proxy" de packeges.json "proxy": "https://www.freetogame.com/", URL base pero aún no puede resolver el problema
FYI: no tengo un código back-end o no uso 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;En realidad, actualmente no está utilizando Rapidapi, está utilizando la API de FreeToGame directamente, si usa Rapidapi, ese problema se resolverá.
El host debe ser: free-to-play-games-database.p.rapidapi.com y, como todas las API de RapidApi, debe incluir la clave de RapidAPI.
Algo como este ejemplo a continuación:
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));