跨域解决
浏览器发起
ajax
需要遵守同源策略
,协议-ip-端口,都必须一致
允许跨域
请求到达网关,网关在请求头中加入Access-Control-Allow-Origin
spring:
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]':
allowedOrigins: "*" #允许所有来源访问
allowedMethods: "*" #允许所有请求方式跨域访问
Access-Control-Allow-Origin
请求头能
支持的请求get、head、post
三种
支持的携带请求头
Content-Type
的值仅限于下列三者之一:告诉服务器这次请求请求体的内容类型。
text/plain
: 提交了大文本multipart/form-data
: 文件上传application/x-www-form-urlencoded
: 普通的表单提交
除此之外的请求,依旧会被拒绝跨域例如
Content-Type:application/json;charser=utf-8
都属于会被拒绝
这类请求在浏览器,发起访问之前,会先发送一个OPTIONS
请求去服务器,询问能否支持跨域
解决方式
网关设置
spring:
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]':
allowedOrigins: "*" #允许所有来源访问
allowedMethods: "*" #允许所有请求方式跨域访问
allowedHeaders: "*" #允许任意请求头跨域
allowCredentials: true #允许Cookie等一些安全标识头跨域
拦截器全局放行
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
public CorsConfig() {
}
@Bean
public CorsFilter corsFilter() {
// 1. 添加cors配置信息
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
// 设置是否发送cookie信息
config.setAllowCredentials(true);
// 设置允许请求的方式
config.addAllowedMethod("*");
// 设置允许的header
config.addAllowedHeader("*");
// 2. 为url添加映射路径
UrlBasedCorsConfigurationSource corsSource = new UrlBasedCorsConfigurationSource();
corsSource.registerCorsConfiguration("/**", config);
// 3. 返回重新定义好的corsSource
return new CorsFilter(corsSource);
}
}