Home > Enterprise >  How to fix CORS error in react vite from front end?
How to fix CORS error in react vite from front end?

Time:11-13

So 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.

My code is the following:

`

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 me and 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.

CodePudding user response:

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.

CodePudding user response:

Since you don't have access to the server you can't do anything from client-side, the only way would be to proxy the request, heroku in not the only platform you can do that with you could create one yourself, or use this service

https://corsproxy.github.io/

CodePudding user response:

To allow the request without cors error you can do only in the backend and not in the frontend. In den backend you have allow request from your frontend domain.

  • Related