CORS(Cross-Origin Resource Sharing)는 웹 애플리케이션이 다른 도메인에서 리소스를 요청할 수 있게해주는 메커니즘을 말한다.
보통 브라우저는 보안상의 이유로 스크립트가 자신의 출처가 아닌 다른 출처의 리소스에 접근하는 것을 금지하기 때문에 프로젝트에서 403과 405 에러로 종종 마주치게된다.
이렇게 발생한 에러는 제한을 완화하여 특정 조건에서만 다른 출처의 리소스 접근을 허용하여 해결한다.
브라우저가 실제 요청을 보내기 전에 서버에 보내는 사전 요청을 말한다.
이는 브라우저가 특정 조건을 충족하는 요청을 보내기 전에 서버가 요청을 허용하는지 확인하기 위해 사용되는데 일반적으로 HTTP 메서드가 GET이나 POST가 아닌 경우, 또는 커스텀 헤더를 사용하는 경우에 발생한다.
Preflight Request의 동작 방식:
전역 설정
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("/**")
.allowedOrigins("http://localhost:3000") // 허용할 출처
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600); // Preflight 요청 캐시 시간
}
};
}
}
Controller 레벨 설정
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@CrossOrigin(origins = "http://localhost:3000")
@GetMapping("/api/data")
public String getData() {
return "Data from server";
}
}