??注:文中的解決方案在 Spring Cloud 2021.0.4、Spring Boot 2.7.4 版本中得到驗(yàn)證,完美解決,其他版本可參考
??請求流程如下圖:通過nginx反向代理到網(wǎng)關(guān),在通過網(wǎng)關(guān)轉(zhuǎn)發(fā)到具體的服務(wù)上
??關(guān)于跨域的理論百度上已經(jīng)有很多,網(wǎng)關(guān)到其他服務(wù)主要是通過注冊中心去找的服務(wù)名在進(jìn)行轉(zhuǎn)發(fā),所以不存在跨域,主要是解決nginx到網(wǎng)關(guān)的跨域問題
方案一:網(wǎng)關(guān)配置類
??在網(wǎng)關(guān)模塊注入跨域配置文章來源:http://www.zghlxwxcb.cn/news/detail-505751.html
@Configuration
public class GlobalCorsConfig {
/**
* 為了安全,建議只放行需要的地址(可以再yaml中定義進(jìn)行映射方便擴(kuò)展)
*/
private List<String> sourceCors = Arrays.asList("http://localhost:8001", "http://localhost:8002", "http://localhost:8003");
private List<String> methods = Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS");
@Bean
public CorsWebFilter corsWebFilter() {
CorsConfiguration config = new CorsConfiguration();
// 放行原始域
if (CollectionUtils.isEmpty(sourceCors)) {
config.addAllowedOrigin("*"); // 放行所有
} else {
for (String sourceCor : sourceCors) {
config.addAllowedOrigin(sourceCor);
}
}
// 放行請求頭
if (CollectionUtils.isEmpty(methods)) {
config.addAllowedHeader("*"); // 放行所有
} else {
for (String method : methods) {
config.addAllowedHeader(method);
}
}
config.setAllowCredentials(true); // 是否發(fā)送cookie
config.addAllowedMethod("*"); // 放行請求方式
config.addExposedHeader("*"); // 暴露頭部信息
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
}
方案一:Gateway yaml 配置
??Gateway 也提供了跨域的配置類,可以直接在yaml中進(jìn)行配置,具體的類配置可以查看源碼 org.springframework.cloud.gateway.config.GlobalCorsProperties文章來源地址http://www.zghlxwxcb.cn/news/detail-505751.html
spring:
cloud:
gateway:
globalcors: # 全局的跨域處理
add-to-simple-url-handler-mapping: true # 解決options請求被攔截問題
corsConfigurations:
'[/**]':
allowedOrigins: # 允許哪些網(wǎng)站的跨域請求 allowedOrigins: “*” 允許所有網(wǎng)站
- "https://localhost:8001"
- "https://localhost:8002"
- "https://localhost:8003"
allowedMethods: # 允許的跨域ajax的請求方式 “*” 允許所有
- "GET"
- "POST"
- "DELETE"
- "PUT"
- "OPTIONS"
allowedHeaders: "*" # 允許在請求中攜帶的頭信息
allowCredentials: true # 是否允許攜帶cookie
maxAge: 360000 # 這次跨域檢測的有效期
到了這里,關(guān)于Spring Cloud Gateway 解決跨域問題的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!