什么是CORS
CORS(Cross-Origin Resource Sharing)“跨域资源共享”,是一个W3C标准,它允许浏览器向跨域服务器发送Ajax请求,打破了Ajax只能访问本站内的资源限制。
什么是跨域请求
大家都知道,现在最常见的开发模式就是前后端分离式开发,而当前端页面想访问后台数据时,就涉及到跨域请求,而跨域请求指的是从一个域名出发去访问另一个域名的资源时,当域名、端口号、协议 任一不同,都称之为跨域请求。
判断是否是跨域请求
例如判断 当通过以下的域名访问? http://www.a.com/test1/index1.html 资源时 是否属于跨域访问
http://www.a.com/test2/index2.html 否
http://www.b.com/test1/index1.html 是,域名不相同
https://www.a.com/test1/index1.html 是,协议不相同
http://www.a.com:8080/test1/index1.html 是,端口号不相同
在SpringBoot中使用CORS实现跨域访问
首先创建两个SpringBoot项目,
项目1 RestFulAPI
1、项目一 RestController
@RestController
@RequestMapping("/api/")
public class ApiController {
@RequestMapping("get")
public HashMap<String, Object> get(@RequestParam String name){
HashMap<String, Object> map = new HashMap<String,Object>();
map.put("name", name);
Student s = new Student(1001, "张三");
map.put("s", s);
return map;
}
}
2、修改项目一端口号
#修改端口号
server:
port: 8092
3、在项目一中编写自定义CORS配置类
/**
* 自定义CORS配置类
*/
@Configuration
public class CustomConfiguration implements WebMvcConfigurer{
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 允许跨域访问的路径 *表示所有路径,可以更换为URL
.allowedOrigins("*") // 允许跨域访问的源
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")// 允许的请求方式
.allowedHeaders("*") //允许的请求头
.maxAge(168000) // 探测请求的有效期
.allowCredentials(true); // 是否发送cookie
}
}
项目2
1、 编写普通Controller
@Controller
@RequestMapping("/")
public class indexController {
@RequestMapping("index")
public String index() {
return "index";
}
}
2、修改项目二端口号
#修改端口号
server:
port: 8091
3、在HTML里使用Ajax测试跨域访问
<script type="text/javascript" src="/webjars/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<h2>index</h2>
<button id='btn1'>按钮</button>
<div id="show"></div>
</body>
<script type="text/javascript">
/*使用AJAX实现跨域请求*/
$("#btn1").click(function(){
$.post(
"http://localhost:8092/api/get",
{
name:"李四"
},
function(map){
$("#show").html(map.s.name);
}
);
});
</script>
4、测试
启动两个项目,
API接口测试:
打开浏览器输入:http://localhost:8092/api/get?name=李四
测试结果如图:
跨域请求测试:
打开浏览器输入:http://localhost:8091/index 点击按钮 测试结果如图:
当然还有另外一种方式, 使用注解:
直接在需要访问的Controller上加上@CrossOrigin注解 即可 (注:需要删除上面的自定义CORS配置类)
@RestController
@CrossOrigin(value="*",maxAge=3600,allowedHeaders="*")
@RequestMapping("/api/")
public class ApiController {
@RequestMapping("get")
public HashMap<String, Object> get(@RequestParam String name){
HashMap<String, Object> map = new HashMap<String,Object>();
map.put("name", name);
Student s = new Student(1001, "张三");
map.put("s", s);
return map;
}
}
为了测试方便,我直接创建了两个项目,项目二就相当于前后端开发时的前端。使用Ajax对后端项目进行跨域访问。
项目二中需要整合Thymeleaf模板 ,可以参考?方案进行整合。
参考资料:SpringBoot整合Thymeleaf模板
本文为初学者学习记录,有什么讲的不对的地方欢迎指出。谢谢!