springboot解决跨域

本地模拟跨域请求以及结果分析

  1. 写一个前端HTML页面放于idea(idea可充当静态web服务器)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CORS跨域</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<div style="text-align:center;margin-top: 100px;font-size: 60px;color: brown;cursor: pointer;">
<span onclick="sendAjaxReq()">发送Ajax请求</span>
</div>
<script type="text/javascript">
function sendAjaxReq() {
$.ajax({
type: "GET",
url: "http://localhost:8080/test/cors",
success: function (message) {
console.log("成功!" + message);
},
error: function (a, b, c) {
console.log("失败!" + a.statusText);
}
});
}
</script>
</body>
</html>
  1. 写一个控制器Controller处理页面发送的ajax请求
1
2
3
4
5
6
7
8
9
10
11
12
/**
* @author cuishiying
* @date 2021-01-22
*/
@RestController
public class CorsController {

@GetMapping("/test/cors")
public Object testCors() {
return "hello cors";
}
}
  1. 利用idea的web服务器能力运行html页面, 地址为: http://localhost:63342/cors-demo/static/index.html

请注意这个页面的访问地址的是 http://localhost:63342/cors-demo/static/index.html,而点击这个"发送Ajax请求"按钮要发送的地址是 http://localhost:8080/test/cors,两者端口号不一样说明是不同的域,因此此ajax请求它必定属于跨域请求(CORS请求)

  1. 点击发送按钮,查看控制台的结果
1
2
Access to XMLHttpRequest at 'http://localhost:8080/test/cors' from origin 'http://localhost:63342' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
失败!error
  1. 配置跨域, 再次访问 http://localhost:63342/cors-demo/static/index.html, 控制台输出 成功!hello cors
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* @author cuishiying
* @date 2021-01-22
*/
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}

@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}

最后

本文到此结束,感谢阅读。如果您觉得不错,请关注公众号【当我遇上你】,您的支持是我写作的最大动力。