공공 API를 호출하는 로직을 작성했는데, 뒤이어 CORS 에러가 발생했다.

import { useEffect, useState } from "react";
import axios from "axios";

const GardenList = () => {
  const [gardenList, setGardenList] = useState<GardenItem[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchGardenList = async () => {
      try {
        const apiKey = process.env.REACT_APP_API_KEY;
        const response = await axios.get(`http://api.nongsaro.go.kr/service/garden/gardenList?apiKey=${apiKey}&pageNo=1&numOfRows=50`);

        const items = response.data?.response?.body?.items?.item || [];
        setGardenList(items);
      } catch (error) {
        console.error('Error fetching garden list:', error);
        setError("An error occurred while fetching the data.");
      } finally {
        setLoading(false);
      }
    };

    fetchGardenList();
  }, []);

CORS 에러란?

CORS (Cross Origin Resource Sharing): 교차 출처 리소스 공유

간단히 말해 출처가 같은 경우에만 서버 간 정보 공유를 할 수 있다는 정책이다.

우선 URL은 아래와 같은 구조로 이루어져있다.

<aside> 💡

http://www.example.com:80/about?q=likes

프로토콜    Host    포트번호   Path   Query string

</aside>

추가로, 특정 번호로 명시된게 아니라면 기본 포트번호는 보통 생략되어있다.

http는 80번, https는 443번이 디폴트이다.