Spring Mvc 跨域访问

Spring Mvc 跨域访问

跨域访问

当前页面渲染请求为 http://localhost:8080/index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>CORS 示例</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="https://code.jquery.com/jquery-3.3.1.min.js" ></script>
</head>
<body>
<div id="message"></div>
</body>
<script>
$(document).ready(function(){
// Ajax 跨域 GET 请求
$.get( "http://api.rest.org:8080/hello", function( data ) {
alert( data );
$( "#message" ).html( data );
});
});
</script>
</html>

注解驱动 @CrossOrigin

  • 在允许跨域访问的接口上添加@CrossOrigin注解
    @CrossOrigin("*")
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

代码驱动 WebMvcConfigurer#addCorsMappings

  • 编写配置类继承WebMvcConfigurer重写addCorsMappings方法
@Configuration
public class RestWebMvcConfigurer implements WebMvcConfigurer {
 public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*");
    }
}

可以看到响应头里含有Access-Controller-Allow-Origin:*的键值对

原文地址:https://www.cnblogs.com/fjf3997/p/13063731.html