CORS policy configuration with React

I would like to access the Discourse API with React.

I get the following error:

localhost/:1 Access to XMLHttpRequest at 'https://community.oppkey.host/posts.json' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

image

This is my CORS origin settings using the Discourse admin panel.

image

On the Discourse server, I have the following in /var/discourse/containers/app.yml

image

This is how I am trying to get the Discourse API.

export const DiscoursePanel = () => {
    const [ allData, updateData ] = useState([]);
	
	useEffect(() => {
         const apiEndPoint = 'https://community.oppkey.host/posts.json';
         /* const apiEndPoint = 'https://jsonplaceholder.typicode.com/posts'; */
        console.log("trying to get API on " + apiEndPoint);
		axios
        .get(apiEndPoint)
		.then((res) => {
			const currentData = res.data;
            updateData(currentData);
            console.log("got api");
            console.log(currentData);
		})
		.catch((err) => console.log(err));
    }, []);

If I use an external server of fake data, the React code works.

image

I don’t understand how CORS and React work in general, so any help would be appreciated.

I have things working with an API proxy server I wrote to relay the API calls from my Discourse server to another REST API server that I’m using to connect to React. Although this works, it is slow. I would like to send API calls direct from React to the Discourse API endpoints.

image

1 me gusta

Hola @codetricity

Lamento que no hayas encontrado una respuesta a esta publicación. Estoy usando React fetch y he pasado por pasos similares a los que mencionaste anteriormente, pero todavía está bloqueando “por política de CORS”.

Por favor, ¿encontraste una solución a este problema o un recurso que explique la solución? ¡Gracias!

Hola, no recuerdo qué terminé haciendo. Sin embargo, acabo de comprobar y el sitio de React sigue funcionando extrayendo datos de Discourse (en un servidor separado).

Dado que usar React con Discourse es común, creo que alguien más podrá responder. Lamento no recordar la solución. Buena suerte.

1 me gusta

Hola
¡Gracias por la rápida respuesta! :slight_smile:

Si tienes un minuto y acceso al mismo código, ¿podrías comprobar si se añadieron encabezados adicionales? (sin la información sensible en sí…)

Dice encima de “No hay encabezado ‘Access-Control-Allow-Origin’” así que creo que deberían haberse añadido encabezados adicionales.

¡Gracias de antemano! :smiley: