pom坐标:spring-cloud-starter-gateway
方式一:bootstrap.yml配置
网关bootstrap.yml增加跨域配置,此配置是最简单的方式,但会有的问题是,其它服务能正常跨域访问,但网关本身的请求会出现,请求不跨域,返回参数跨域的问题,如果能在代码层面解决该问题,烦请告知,谢谢。
spring:
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]':
allow-credentials: true
allowed-origins: "*"
allowed-headers: "*"
# 允许跨域的method
allowed-methods:
- OPTIONS
- GET
- POST
# 允许跨域的时间
max-age: 3600
方式二:新增配置类
在网关层增加该配置类即可解决方式一的网管层返回跨域问题
package com.xrkc.gateway.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
/**
* @Description:跨域配置
* @Auther: wangjiao
* @Date: 2021-05-18 09:23
*/
@Configuration
public class CorsConfig {
@Bean
public CorsWebFilter corsWebFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(source);
}
}
以上两种方式,人选其一即可。
本文介绍如何为 Spring Cloud Gateway 进行跨域配置,提供了两种方式:一是通过 bootstrap.yml 文件配置,二是通过新增配置类 CorsConfig 解决跨域问题。
7546

被折叠的 条评论
为什么被折叠?



