XMLHttpRequest, Fetch API, <img> 등의 방식으로 리소스를 요청.클라이언트 요청에는 Origin 헤더가 포함되어 출처 정보를 브라우저가 서버로 전달.
GET /data HTTP/1.1
Host: api.example.com
Origin: http://frontend.example.com
서버는 클라이언트 요청을 허용할지 응답 헤더로 전달.
| 헤더 이름 | 설명 |
|---|---|
Access-Control-Allow-Origin | 허용된 출처. 특정 도메인, 또는 *(모두 허용). |
Access-Control-Allow-Methods | 허용된 HTTP 메서드 목록 (예: GET, POST, PUT). |
Access-Control-Allow-Headers | 허용된 요청 헤더 목록 (예: Content-Type, Authorization). |
Access-Control-Allow-Credentials | 인증 정보를 포함한 요청(쿠키 등)을 허용할지 여부. |
Access-Control-Expose-Headers | 클라이언트가 접근 가능한 응답 헤더. |
Access-Control-Max-Age | 사전 요청(preflight)의 결과를 캐시하는 시간(초 단위). |
GET, POST, HEAD 중 하나.Content-Type, Accept, Origin 등).GET /data HTTP/1.1
Origin: http://frontend.example.comPUT, DELETE)은 서버에 사전 요청을 전송하여 허용 여부를 확인.OPTIONS /data HTTP/1.1
Origin: http://frontend.example.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: http://frontend.example.com
Access-Control-Allow-Methods: POST, GET
Access-Control-Allow-Headers: Content-Type
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ApiController {
@CrossOrigin(origins = "http://frontend.example.com")
@GetMapping("/data")
public String getData() {
return "CORS 설정된 데이터";
}
}
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 implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 모든 엔드포인트에 대해 CORS 허용
.allowedOrigins("http://frontend.example.com") // 허용된 출처
.allowedMethods("GET", "POST", "PUT", "DELETE") // 허용된 메서드
.allowedHeaders("*") // 모든 요청 헤더 허용
.allowCredentials(true) // 쿠키 전송 허용
.maxAge(3600); // 1시간 동안 캐시
}
}
# 스프링 부트 2.4 이상에서 글로벌 CORS 설정 지원
spring.web.cors.allowed-origins=http://frontend.example.com
spring.web.cors.allowed-methods=GET,POST,PUT,DELETE
spring.web.cors.allowed-headers=*
spring.web.cors.allow-credentials=true
Access-Control-Allow-Origin 헤더를 반환하도록 설정.Origin, Access-Control-Request-Headers)를 점검.package.json):"proxy": "http://localhost:8080"Access-Control-Allow-Origin: * 대신 필요한 도메인만 허용.