- 为什么又跨域这个问题的出现
-
- 这是浏览器的一个保护机制
- 因为浏览器有同源策略(安全策略)
- 什么是同源:(url中)
-
-
-
- 协议
- 域名
- 端口
- 这三个相同就是同源(必须一致),如果不一致,就导致了跨域问题的出现
- 使用CORS解决
-
- 什么是cors(Cross Origin Resource Sharing:跨域资源共享)
- 它由一系列传输的[HTTP头]组成
2.这些HTTP头决定浏览器是否阻止前端 JavaScript 代码获取跨域请求的响应。
///Spring Boot项目中解决跨域的3种方案
//使用cros的原理是,每次请求之后,后端返回给前端的响应,他的响应头都会进行设置资源共享
1、在Controller方法上添加@CrossOrigin 注解
@GetMapping("/list")
@CrossOrigin
public List<String> List(){}
//但是这个方法需要每个Controller都要添加,很麻烦
2.添加cors过滤器,解决每个方法都要加CrossOrigin问题
在配置包中(configuration)添加cors过滤器(CorsConfig)
@Configuration
public class CorsConfig(){
@Bean
public CorsFilter crosFilter(){
//创建CorsConfiguration对象
CorsConfiguration corsConfiguration = new CrosConfiguration();
//允许所有的请求都可以通过
corsConfiguration.addAllowedOrigin("*");
//设置请求头字段
corsCofniguration.addAllowedHeader("*");
//请求的方式(get,post)
corsConfiguration.addAllowedMethod("*");
//创建source对象
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//将你要请求的路径进行设置(请求路径,配置类)
source.registerCorsConfiguration("/**",crosConfiguration);
return new Corsfilter(source);
}
}
//3.使用接口的形式
//实现webMvcConfigurer接口,重写addCorsMapping方法
@configuration
public class corsconfig implements WebMvcConfigurer {
@override
public void addCorsMappings(corsRegistry registry){
egistry.addMapping("/**")//允许跨域访问的路径
.allowedorigins("*")//允许所有的请求
.allowedHethods("POST","GET","PUT","OPTIONS","DELETED")//允许请求方法
.maxAge(168000)//设置预验间隔时间
.allowedHeaders("*")//允许头部设置
.allowcredentials(true);//是否发送cookie
}
}