miin29na

[Spring] Access-Control-Allow-Origin 에러 본문

IT_Spring/spring

[Spring] Access-Control-Allow-Origin 에러

miin29na 2020. 2. 17. 19:03

Spring 기반 Server Rest API 를 javascript 로 테스트 도중  다음과 같은 에러가 발생(크롬)

로컬 개발 서버에서는 Success, 원격 배포 서버에서는 Fail.


index.html:1 Access to XMLHttpRequest at 'http://원격지:8080/abc/' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
index2.html:154 {readyState: 0, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, override

 

 

Server side solution)

1. 

1
2
3
4
5
6
7
8
9
@Configuration 
public class WebMvcConfig implements WebMvcConfigurer { 
 
    @Override 
     public void addCorsMappings(CorsRegistry registry) { 
        registry.addMapping("/**").allowedOrigins("*"); 
   } 
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

 or

 

2.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 @Bean 
 public CorsConfigurationSource corsConfigurationSource() { 
CorsConfiguration configuration = new CorsConfiguration(); 
configuration.addAllowedOrigin("*");  // CORS 요청 허용 Site
configuration.addAllowedMethod("*");  // CORS 요청 허용 Method Type (e.g. GET,PUT,POST)
configuration.addAllowedHeader("*"); // 특정 헤더 CORS 요청 허용
configuration.setAllowCredentials(true); // 자격증명과 함께 요청 여부 (Authorization로 사용자 인증 사용 시 true)
configuration.setMaxAge(3600L); // preflight request cache time
  
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 
source.registerCorsConfiguration("/**", configuration); 
return source; 
}
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

 

refrence link

https://brunch.co.kr/@adrenalinee31/1

 

javascript ajax 크로스도메인 요청-CORS

web application development | Overview 웹 개발시 자바스크립트로 외부 서버의 경로로 ajax요청을 날리면 에러가 나면서 요청이 실패한다. 웹 브라우저의 콘솔 창에 아래와 같은 메시지를 보게 된다. 크롬 No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ‘[요청한 도메인]' is

brunch.co.kr

https://spring.io/guides/gs/rest-service-cors/

 

Enabling Cross Origin Requests for a RESTful Web Service

this guide is designed to get you productive as quickly as possible and using the latest Spring project releases and techniques as recommended by the Spring team

spring.io

 

Comments