什么是跨域
如果请求地址里的协议、域名、端口号都相同就属于同源。任何一共不同就是跨域
http://www.a.com/a/a.html 和 http://www.a.com/b/b.html 同源
http://www.a.com/a/a.html 和 http://www.b.com/a/a.html 跨域 域名不同
http://www.a.com/a/a.html 和 https://www.a.com/b/b.html 跨域 协议不同
http://www.a.com/a/a.html 和 http://www.a.com:8080/b/b.html 跨域 端口不同
CORS是W3C提出的跨域资源共享方案,CORS将请求分为两大类:简单请求和非简单请求
只要同时满足以下两大条件,就属于简单请求。
(1) 请求方法是以下三种方法之一:
- HEAD
- GET
- POST
(2)HTTP的头信息不超出以下几种字段:
- Accept
- Accept-Language
- Content-Language
- Last-Event-ID
- Content-Type:只限于三个值
application/x-www-form-urlencoded
、multipart/form-data
、text/plain
凡是不同时满足上面两个条件,就属于非简单请求。
浏览器发起跨源请求,就会自动添加一些附加的头信息,有时还会多出一次附加的请求,但用户不会有感觉。
因此,实现CORS通信的关键是服务器。只要服务器实现了CORS接口,就可以跨源通信。
CORS技术可以在不破坏既有规则的情况下,通过后端服务器实现CORS接口,从而实现跨域通信
CORS实现也比较简单,在config包下新增CORS配置类,实现WebMvcConfigurer接口,代码如下:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 允许跨域访问的路径
.allowedOrigins("*") // 允许跨域访问的源
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE") // 允许请求方法
.maxAge(168000) // 预检间隔时间
.allowedHeaders("*") // 允许头部设置
.allowCredentials(true); // 是否发送cookie
}
}
如果访问报错,When allowCredentials is true, allowedOrigins cannot contain the special value “*“ since that cannot
是因为新的springboot版本中,跨域配置需要将 .allowedOrigins 替换成 .allowedOriginPatterns,如下图