AdSaMo
AdSaMo

Reputation: 39

How to fix CORS error in react + vite from front end?

I am trying to fetch data from an API but it keeps showing a CORS error no matter what I try... enter image description here

It is important to know that It is an external API and I don't have access to the server code. Only to my front-end code.

Here is my code:

const [contaminacion, setcontaminacion] = useState([]);

 
  const obtenerDatos = async (url) => {
    const datan = await fetch(url, {
      mode: "cors",
      method:"GET",
      headers: {
        "Access-Control-Allow-Origin": "*",
        "cache-control": "no-cache",
      },
    });
    console.log(datan);
    const dataParsed = await datan.json();
    setcontaminacion(dataParsed.results);
  };

  
  useEffect(() => {
    obtenerDatos(
      "https://opendata.aemet.es/opendata/api/red/especial/contaminacionfondo/estacion/07"
    );
    
  }, []);

I read in an old post (more than 5 years old) that I could use a proxy with Heroku, but in the comments they say that Heroku doesn't serve to this purpose anymore.

I have tried to set a proxy in my vite.config.js folder but it is not working for I don't know if I am doing it properly or not.

That's what I wrote:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  server:{
    proxy:{
      '/api': {
        target: 'https://opendata.aemet.es/opendata/api/red/especial/contaminacionfondo/estacion/07',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
      
    }

  },
  plugins: [react()]
})

What am I missing here? Any help would be appreciated.

Upvotes: 0

Views: 12910

Answers (2)

Caden Wen
Caden Wen

Reputation: 7

don’t know why but it works

const axiosInstance = axios.create({
  baseURL: "http://localhost:8000",
  headers: {
    "Access-Control-Allow-Origin": "*",
    "Content-Type": "application/json", //this line solved cors
  },
});

Upvotes: -2

Nithin Kumar Biliya
Nithin Kumar Biliya

Reputation: 3011

You cannot use https://opendata.aemet.es/centrodedescargas/inicio APIs without an API key.

You will have to register on the site, get an API key and using that API make the request. When registering for the API key, you will be asked to provide the domain of your application. This domain will be returned in the Access-Control-Allow-Origin header and your client will not get the CORS error anymore.

Upvotes: 0

Related Questions