需求简述
用GateWay做代理,进行请求。
具体操作过程
- pom文件添加gateway依赖
- 添加了跨域配置
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.maxAge(3600);
}
}
- 在最后启动的时候出现了如下问题
Spring MVC found on classpath, which is incompatible with Spring Cloud Gateway.
问题解决
由于引入了web依赖,而没有编写controller层相关接口,所以会报错。将spring-boot-starter-web依赖去掉即可。
同时把跨域配置改成如下实现:
@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);
}
}