웹개발/스프링부트
스프링부트 CORS 적용하기
어컴띵
2021. 2. 17. 23:23
클라이언트에서 api 호출시 다음과 같은 에러가 날때가 있다.
Access to fetch at 'http://localhost:8080/api/v1/hello' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
이오류에 대해서는 다음을 참조하자
developer.mozilla.org/ko/docs/Web/HTTP/CORS
교차 출처 리소스 공유 (CORS) - HTTP | MDN
이에 대한 응답으로 서버는 Access-Control-Allow-Origin 헤더를 다시 보냅니다. 교차 출처 리소스 공유(Cross-Origin Resource Sharing, CORS)는 추가 HTTP 헤더를 사용하여, 한 출처에서 실행 중인 웹 애플리케이
developer.mozilla.org
이런 오류가 날때 다음과 같이 bean을 설정하면 CORS를 오류없이 클라이언트에서 api를 호출 할수 있게 된다.
@Bean
public WebMvcConfigurer corsConfigurer(){
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:3000");
}
};
}