SPRING BOOT 에서의 CORS설정
(1) 전역 설정
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 implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("https://example.com") // 허용할 도메인 설정
.allowedMethods("GET", "POST", "PUT", "DELETE") // 허용할 HTTP 메서드 설정
.allowedHeaders("*")
.allowCredentials(true);
}
}
(2) 개별 컨트롤러에서 설정
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 = "https://example.com")
@GetMapping("/data")
public String getData() {
return "CORS 설정된 데이터";
}
}
위와 같이 헤더를 설정해주면 브라우저가 검토하여 허용되는지 확인한다.
제어 -> 서버 , 수행 -> 브라우저
주로 브라우저에서 발생
방법1) 로컬환경에서 api를 테스트시에는 chrome 확장 프로그램 사용 (allow cors프로그램)
빠르게 대처가능
방법2) proxy사이틑 이용하기
서버에서 따로 cors설정을 안해주었다면 모든 출처를 허용한 proxy 사이트를 이용하면 된다.
( proxy 사이트를 이용하면 CORS 정책을 적용하지 않고도 다른 도메인에서의 리소스를 요청할 수 있다.)
방법3) 서버에서 Access-control-Allow-Origin 헤더 세팅하기(cors헤더 세팅하기)
spring , apache , tomcat에서 가능