spring boot

前后端分离项目,引入Spring Cloud Gateway遇到

2020-01-07  本文已影响0人  macrozheng

随着项目架构的越来越复杂,引入了新的技术,新的问题也在产生,本文将讲述一个由于网关引起的前端调用问题。

SpringBoot实战电商项目mall(25k+star)地址:https://github.com/macrozheng/mall

问题产生

我的mall项目升级到微服务架构以后,加入了基于Spring Cloud Gateway的网关系统,前端调用相关服务时应该统一从网关进行调用,本以为前端直接调用网关没啥问题,后来发现会产生无法调用的情况,下面我们来记录下这个问题以及解决思路。

问题重现与解决

这里我们以mall-swarm中的代码为例来演示下该问题的产生与解决。

image image
/**
 * 全局跨域配置
 * 注意:前端从网关进行调用时需要配置
 * Created by macro on 2019/7/27.
 */
@Configuration
public class GlobalCorsConfig {

    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }

}
image
/**
 * 全局跨域配置
 * 注意:前端从网关进行调用时不需要配置
 * Created by macro on 2019/7/27.
 */
//@Configuration
public class GlobalCorsConfig {

    /**
     * 允许跨域调用的过滤器
     */
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        //允许所有域名进行跨域调用
        config.addAllowedOrigin("*");
        //允许跨越发送cookie
        config.setAllowCredentials(true);
        //放行全部原始头信息
        config.addAllowedHeader("*");
        //允许所有请求方法跨域调用
        config.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}
image

总结

当前端应用通过网关调用服务时会产生跨域问题,解决方法是在网关服务中进行全局跨域配置,同时相关服务中如果有跨域配置应该去除。

项目地址

https://github.com/macrozheng/mall-swarm

公众号

mall项目全套学习教程连载中,关注公众号第一时间获取。

公众号图片
上一篇 下一篇

猜你喜欢

热点阅读