반응형
CORS 란
CORS는 Cross-Origin Resource Sharing의 줄임말로 교차-출처 리소스 공유하고도 한다.
즉, 다른 출처라고도 말할 수 있고 다른 출처이기 때문에 발생하는 에러라고도 할 수 있다.
next.config.mjs 설정
** next.config.mjs **
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
async rewrites() {
return [
{
source: '/api/:path*',
destination: 'http://apis.data.go.kr/B552584/ArpltnInforInqireSvc/:path*',
},
];
},
};
export default nextConfig;
위 설정 파일로 proxy 설정을 하여 CORS 에러에 대응할 수 있다.
rewrites 함수를 이용해 URL로 우회하여 요청하여 cors에러를 피할 수 있다.
설정 완료 후 페이지에서 api 요청을 할 때 우회한 url을 넣어줘야 한다.
** page.js **
export default function Home() {
const api_url =
'/api/getMsrstnAcctoRltmMesureDnsty?stationName=종로구&dataTerm=month&pageNo=1&numOfRows=100&returnType=json&serviceKey=서비스키';
const [list, setList] = useState([]);
const getData = () => {
axios.get(api_url).then((res) => setList(res.data.response.body.items));
};
// 최초 한번만 호출하기 위해 사용함!
useEffect(() => {
getData();
}, []);
return (
<main style={{ width: '80%', padding: '20px', margin: 'auto' }}>
{list.map((el) => (
<p key={el.dataTime}>{el.khaiValue}</p>
))}
</main>
);
}
config 파일에서 source로 입력한 경로로 우회해 사용했는데
데이터가 잘넘어 오고 CORS 에러가 발생하지 않았다.
반응형
'nextjs' 카테고리의 다른 글
[nextjs] next.js 기본 개념 / 설치 (0) | 2023.09.02 |
---|