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 „Gefällt mir“

Hallo @codetricity

Entschuldige, dass du keine Antwort auf diesen Beitrag gefunden hast. Ich verwende React fetch und habe ähnliche Schritte wie die von dir oben erwähnten unternommen, aber es wird immer noch mit „CORS-Richtlinie blockiert“ abgebrochen.

Hast du eine Lösung für dieses Problem oder eine Ressource gefunden, die die Lösung erklärt? Danke!

Hallo, ich kann mich nicht erinnern, was ich am Ende getan habe. Ich habe gerade nachgesehen und die React-Website wird immer noch mit Daten von Discourse (auf einem separaten Server) angezeigt.

Da die Verwendung von React mit Discourse üblich ist, denke ich, dass jemand anderes sie beantworten kann. Es tut mir leid, dass ich mich nicht an die Lösung erinnern kann. Viel Glück.

1 „Gefällt mir“

Hallo
Danke für die schnelle Antwort! :slight_smile:

Wenn Sie eine Minute Zeit und Zugriff auf denselben Code haben, könnten Sie bitte prüfen, ob zusätzliche Header hinzugefügt wurden? (ohne die sensiblen Informationen selbst…)

Dort steht über dem „Kein 'Access-Control-Allow-Origin'-Header vorhanden“, dass zusätzliche Header hätten hinzugefügt werden sollen?

Vielen Dank im Voraus! :smiley: