跨域
指的是浏览器不能执行其他网站的脚本。它是由浏览器的 同源策略 造成的,是浏览器对js施加的安全限制。(ajax可以)
同源策略
是指 协议,域名,端囗 都要相同,其中有一个不同都会产生跨域
示例:
跨域流程
预检请求options
简单请求不会触发CORS预检请求,“简属于
单请求”术语并不属于Fetch(其中定义了CORS)规范。
若满足所有下述条件,则该请求可视为“简单请求”:
- 使用下列方法之一:
- GET
- HEAD
- POST
- Content-Type: (仅当POST方法的Content-Type值等于下列之一才算做简单需求)
- text/plain
- multipart/form-data
- application/x-www-form-urlencoded
解决跨域问题
在gateway网关中定义一个过滤器配置文件.
基本思想:需要一个CorsWebFilter,然后缺什么new 什么。是接口找实现类
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
@Bean // 添加过滤器
public CorsWebFilter corsWebFilter(){
// 基于url跨域,选择reactive包下的
UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource();
// 跨域配置信息
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 允许跨域的头
corsConfiguration.addAllowedHeader("*");
// 允许跨域的请求方式
corsConfiguration.addAllowedMethod("*");
// 允许跨域的请求来源
corsConfiguration.addAllowedOriginPattern("*");
// 是否允许携带cookie跨域
corsConfiguration.setAllowCredentials(true);
// 任意url都要进行跨域配置
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(source);
}