跨域
浏览器同源策略
1995
年,同源政策由
Netscape
公司引入浏览器。目前,所有浏览器都实行
这个政策。 最初,它的含义是指,
A
网页设置的
Cookie
,
B
网页不能打开,除非这两个网
页
"
同源
"
。所谓
"
同源
"
指的是
"
三个相同
"
解决方法
JSONP
页面这层再包装一层服务,目前最多就是
nodejs
Http
响应头配置允许跨域
nginx
代理服务器
后端程序代码配置
协议相同
http https
域名相同
www.xdclass.net
端口相同
80 81
一句话:浏览器从一个域名的网页去请求另一个域名的资源时,域名、端口、协议任一不同,都是跨域
浏览器控制台跨域提示:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'null' is therefore not allowed access.
程序代码中处理
SpringBoot
通过拦截器配置
//
表示接受任意域名的请求
,
也可以指定域名
response.setHeader("Access-Control-Allow-Origin",
request.getHeader("origin"));
//
该字段可选,是个布尔值,表示是否可以携带
cookie
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST,
PUT, PATCH, DELETE, OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "*");