본문 바로가기
Q&A2022년 3월 20일1분 읽기

CORS 에러 해결 방법 정리

김
김민수
조회 650댓글 2

프론트엔드 개발할 때 CORS 에러가 너무 자주 나옵니다. 해결 방법을 정리해주세요.

댓글 2

김김영삼4년 전

CORS 에러 상황별 해결:

1. 백엔드에서 헤더 설정 (근본 해결):

// Express.js
const cors = require("cors");
app.use(cors({ origin: "https://mysite.com", credentials: true }));

// Nginx
add_header Access-Control-Allow-Origin "https://mysite.com";
add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE";
add_header Access-Control-Allow-Headers "Content-Type, Authorization";

2. 개발 중 프록시:

// Next.js next.config.js
async rewrites() {
return [{ source: "/api/:path*", destination: "http://localhost:8080/api/:path*" }];
}

// Vite vite.config.js
server: { proxy: { "/api": "http://localhost:8080" } }

3. Preflight 요청 처리:

// OPTIONS 요청에 대한 응답
app.options("*", cors());

브라우저 확장으로 CORS를 끄는 건 절대 프로덕션 해결책이 아닙니다.

허허진우(guest)4년 전
자세한 설명 감사합니다.
Ctrl+Enter로 등록