前言
在《Spring boot开发实战》的跨域配置的例子中,总觉得有什么地方怪怪的,所以写下博客理通一下。
跨域流程
- 前端 8081 端口 的index.html页面
<!DOCTYPE html>
<html lang="en" xmlns:http="http://www.springframework.org/schema/mvc">
<head>
<meta charset="UTF-8">
<title>title</title>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
</head>
<body>
<div id="contentDiv"></div>
<div id="deleteResult"></div>
<input type="button" value="提交数据" onclick="getData()"><br>
<input type="button" value="删除数据" onclick="deleteData()"><br>
<script>
function deleteData() {
$.ajax({
url:'http://localhost:8080/origin/99',
type:'delete',
success:function (msg) {
$("#deleteResult").html(msg)
}
})
}
function getData() {
$.ajax({
url:'http://localhost:8080/origin/',
type:'post',
data:{name:'三国演艺'},
success:function (msg) {
$("#contentDiv").html(msg)
}
})
}
</script>
</body>
</html>
前端的ajax请求地址是8080端口的
2. 后端8080端口的 controller配置
@RestController // 代替 controller 和 ResponseBody
@RequestMapping("/origin")
public class OriginController {
@PostMapping("/")
@CrossOrigin(value = "http://localhost:8081",maxAge = 1800,allowedHeaders = "*")
public String addBook(String name){
System.out.println("111");
return "receive:"+name;
}
@DeleteMapping("/{id}")
@CrossOrigin(value = "http://localhost:8081",maxAge = 1800,allowedHeaders = "*")
public String deleteBookById(@PathVariable Long id){
System.out.println("222");
return String.valueOf(id);
}
}
value的属性值表示支持的域。
3. 访问 8081 端口的html页面
页面访问的是8081端口,请求响应的后台是8080端口的后台。可以看到请求头中 Origin 是 81端口,Host 是 80端口。
总结
前端所在页面是81端口,请求的url是80端口,响应的后台是80端口,后台controller中@CrossOrigin的value配置的是允许81端口的域名访问。所以就形成了跨域。