[스프링 부트] chapter 24. 스프링 웹 MVC 11부 CORS
스프링 웹 MVC 11부 CORS
SOP과 CORS
-
Single-Origin Policy
-
Cross-Origin Resource Sharing
-
Origin?
- URI 스키마 (http, https)
- hostname (juho.com, localhost)
- 포트 (8080, 18080)
스프링 MVC @CrossOrigin
-
https://docs.spring.io/spring/docs/5.0.7.REALEAS/spring-framework-reference/web.html#mvc-cors
-
@Controller나 @RequestMapping에 추가하거나
@RestController
@SpringBootApplication
public class SpringcorsserverApplication {
@CrossOrigin(origins = "[http://localhost:18080](http://localhost:18080/)")
@GetMapping("/hello")
public String hello() {
return "hello";
}
public static void main(String[] args) {
SpringApplication.run(SpringcorsserverApplication.class, args);
}
}
- WebMvcConfigurer 사용해서 글로벌 설정
@RestController
@SpringBootApplication
public class SpringcorsserverApplication {
@GetMapping("/hello")
public String hello() {
return "hello";
}
public static void main(String[] args) {
SpringApplication.run(SpringcorsserverApplication.class, args);
}
}
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("[http://localhost:18080](http://localhost:18080/)");
}
}
- ajax 테스트용 소스
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello Title</title>
</head>
<body>
Hello static resources
<script src="/webjars/jquery/dist/jquery.min.js"></script>
<script>
$(function() {
$.ajax("<http://localhost:7777/hello>")
.done(function(msg) {
alert(msg);
})
.fail(function() {
alert("alert")
});
});
</script>
</body>
</html>
<!DOCTYPE html>