Discourse API を React で利用したいと考えています。
以下のエラーが発生します:
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.
Discourse の管理パネルで設定している CORS 元設定は以下の通りです。
Discourse サーバー側では、/var/discourse/containers/app.yml に以下が設定されています。
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));
}, []);
外部のダミーデータサーバーを使用すれば、React のコードは正常に動作します。
CORS と React の仕組みについて全体的に理解できていないため、ご助言いただけますと幸いです。
現在、私が作成した API プロキシサーバーを介して、Discourse サーバーからの API 呼び出しを別の REST API サーバーに中継し、React と接続する仕組みは動作しています。ただし、この方法では速度が遅いです。React から直接 Discourse の API エンドポイントへ API 呼び出しを送信したいと考えています。




