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:

如果您有时间并且可以访问相同的代码,能否请您检查是否添加了其他标头?(不包含敏感信息……)

上面写着“No 'Access-Control-Allow-Origin' header is present”,所以您认为应该添加其他标头吗?

提前感谢! :smiley: