一、介绍
1.1 为什么会出现跨域?
出于浏览器的同源策略限制。同源策略(Sameoriginpolicy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说 Web 是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。同源策略会阻止一个域的javascript脚本和另外一个域的内容进行交互。所谓同源(即指在同一个域)就是两个页面具有相同的协议(protocol),主机(host)和端口号(port)
1.2 什么是跨域?
当一个请求 url 的协议、域名、端口三者之间任意一个与当前页面 url 不同即为跨域
| 请求页面url | 当前页面url | 是否跨域 | 原因 |
| http://www.test.com/ | http://www.test.com/index.html | 否 | 同源(协议、域名、端口号相同) |
| http://www.test.com/ | https://www.test.com/index.html | 跨域 | 协议不同(http/https) |
| http://www.test.com/ | http://www.baidu.com/ | 跨域 | 主域名不同(test/baidu) |
| http://www.test.com/ | http://blog.test.com/ | 跨域 | 子域名不同(www/blog) |
| http://www.test.com:8080/ | http://www.test.com:7001/ | 跨域 | 端口号不同(8080/7001) |
1.3 非同源限制
【1】无法读取非同源网页的 Cookie、LocalStorage 和 IndexedDB
【2】无法接触非同源网页的 DOM
【3】无法向非同源地址发送 AJAX 请求
二、案例
假设我们是前后段分离的项目,分别部署在以下两个ip上
前端页面的地址为 http://127.0.0.1:8848/test/index.html
后台服务的地址为 http://99.48.59.195:8082/
前后端的主要代码如下所示:
后端接口 HelloController.java
import com.example.security.entity.User; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.Map; @RestController public class HelloController { @GetMapping("/testGet") public String testGet(String username) { return username; } @GetMapping("/testGet2") public String testGet2(String username, String password) { return username + "," + password; } @PostMapping("/testPost") public Map testPost(@RequestBody Map<String, Object> map) { return map; } @PostMapping("/testPost2") public User testPost2(User user) { return user; } }