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)

مرحباً @codetricity

عذرًا لم تجد ردًا على هذا المنشور. أنا أستخدم React fetch وقد مررت بخطوات مماثلة لتلك التي ذكرتها أعلاه ولكنها لا تزال محظورة “بسبب سياسة CORS”.

هل وجدت حلاً لهذه المشكلة أو موردًا يشرح الحل؟ شكرًا!

مرحباً، لا أستطيع تذكر ما فعلته في النهاية. على الرغم من ذلك، لقد تحققت للتو ولا يزال موقع React يعمل ويجلب البيانات من Discourse (على خادم منفصل).

نظرًا لأن استخدام React مع Discourse شائع، أعتقد أن شخصًا آخر سيكون قادرًا على الإجابة. يؤسفني أنني لا أستطيع تذكر الحل. حظاً موفقاً.

إعجاب واحد (1)

مرحباً
شكراً على الرد السريع! :slight_smile:

إذا كان لديك دقيقة ووقت للوصول إلى نفس الكود، هل يمكنك التحقق مما إذا تمت إضافة رؤوس إضافية؟ (بدون المعلومات الحساسة نفسها…)

يقول أعلاه “لا يوجد رأس ‘Access-Control-Allow-Origin’” لذلك أعتقد أنه كان يجب إضافة رؤوس إضافية؟

شكراً مقدماً! :smiley: