본문 바로가기

Java/Spring Boot

SpringBoot-010-CORS (Cross Origin Resource Sharing)

0. CORS란?

- Cross-Site HTTP Request를 가능하게 하는 표준 규약

- 자세한 내용 참고: 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

1. CORS 실습

두개의 프로젝트를 생성 한다(즉 두개의 서버가 필요)

 

1) ajax를 통해 Rsource를 요청받는 웹애플리케이션 생성

- src/main/java-config-CorsConfig.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class CorsConfig implements WebMvcConfigurer{
 
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowedMethods("*");
    }
    
    
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

src/main/java-controller-TestController.java (테스트를 위해 간단히 RestController...)

1
2
3
4
5
6
7
8
9
10
11
12
13
 
@RestController
public class TestController {
 
    @RequestMapping("/test")
    public String test() {
        return "성공했습니다!";
    }
    
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

 

2) 직접 Resource를 요청받는 웹애플리케이션 생성

 

- application.properties에 server.port=18080 추가

- build.gradle에 compile 'org.webjars.bower:jquery:3.4.1' 추가

- build.gradle에 compile 'org.webjars:webjars-locator-core' 추가

- src/main/resources/static-index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CORS 테스트</title>
</head>
<body>
    
    환영합니다.;
    
<script src="/webjars/jquery/dist/jquery.min.js"></script>
<script>
 
    $(function () {
        $.ajax("http://localhost:8080/origin").done(function(msg){
                alert(msg);
            }).fail(function(){ alert("fail...");
        });
    });
</script>
 
</body>
</html>
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

 

반응형