Project/profile-service

CORS (Cross-Origin Resource Sharing) 오류 해결 방법

개발자겨려 2025. 4. 28. 19:36

CORS (Cross-Origin Resource Sharing)란?

CORS는 웹 페이지가 다른 도메인의 리소스에 접근할 수 있도록 브라우저에게 권한을 부여하는 체제이다. 브라우저는 보안상의 이유로 다른 출처(Origin)의 리소스에 대한 HTTP 요청을 제한하는데, 이때 출처는 프로토콜, 호스트, 포트를 포함한다. 즉, CORS는 웹 페이지가 다른 출처의 자원을 요청하는 것을 제한하는 보안 메커니즘이라고 생각하면 된다.

 

나의 경우에는

  • React는 localhost:3000
  • Spring Boot는 localhost:8080

서로 포트가 다르기 때문에 "다른 출처(Cross-Origin)"로 인식함.

특히 PUT, POST 요청은 CORS preflight(사전 요청) 검사를 거치는데, 이걸 Spring 서버가 거부해서 403 에러가 났다

 

 

1. Proxy 설정 (React 개발 서버가 /api로 오는 요청을 8080번 백엔드로 포워딩)

 

🔥방법 1) package.json 파일에 "proxy" : "httpp://localhost:8080"  추가

        👉 이것은 컴퓨터가 랜선에 연결되어있다면 오류가 나올 가능성이 크다

 

🔥방법 2) http-proxy-middleware 라이브러리를 이용 (추천)

  • frontend 폴더에서 http-proxy-middleware를 설치
    npm install http-proxy-middleware --save​
  • src/setupProxy.js 파일을 생성하고 다음 코드를 추가(changeOrigin: true는 대상 서버가 요청의 원래 호스트 이름을 볼 수 있도록 한다) 
    //setupProxy.js
    const { createProxyMiddleware } = require("http-proxy-middleware");
    
    module.exports = function (app) {
        app.use(
            "/api",
            createProxyMiddleware({
                target: "http://localhost:8080",
                changeOrigin: true,
            })
        );
    };
  • API 요청 시 /api 경로를 사용한다.
    fetch('/api/todos')
      .then(response => response.json())
      .then(data => console.log(data));

 

             

 

 

2. 백엔드(Spring Boot)에서 CORS 설정

 

🔥방법 1. Spring Boot에 CORS 허용 설정 추가 ( 가장 빠른 방법 )

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/member-profiles")
@CrossOrigin(origins = "http://localhost:3000") // 이거 추가!!
public class MemberController {
    // ...
}​

 

🔥방법 2. WebMvcConfigurer로 전역 설정 

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**")
                        .allowedOrigins("http://localhost:3000")
                        .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                        .allowCredentials(true);
            }
        };
    }
}