spring cloud Gateway 处理跨域问题
先简单描述一下架构,项目采用前后端分离的方式,前端是nodejs来搞layui(单页版),后端采用spring cloud Alibaba,网关用的是spring cloud Gateway,然后出现了跨域问题。一开始百度我以为只需要在Controller上加上@CrossOrigin就能搞定,后来发现出现了很多问题。
问题一:
因为后端还有网关,所以如果你没有自定的headers的头信息那么是可以通过 spring cloud Gateway ,但是如果有加自定义Headers,这样就会被 spring cloud Gateway给拦截,说:跨域请求中没有自定的header
错误信息如下
考虑之后觉得应该需要在spring cloud Gateway上添加跨域配置
添加方式有许多种,这里我写出尝试过可以用的两种:
一在application.yml中添加配置
spring: application: name: nb-web cloud: nacos: discovery: server-addr: localhost:8848 gateway: globalcors: corsConfigurations: '[/**]': allowedHeaders: "*" allowedOrigins: "*" allowCredentials: true allowedMethods: - GET - POST - DELETE - PUT - OPTION
第二种再启动类上添加bean:
/** * 配置跨域 * @return */ @Bean public CorsWebFilter corsFilter() { CorsConfiguration config = new CorsConfiguration(); // cookie跨域 config.setAllowCredentials(Boolean.TRUE); config.addAllowedMethod("*"); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); // 配置前端js允许访问的自定义响应头 config.addExposedHeader("Authorization:"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser()); source.registerCorsConfiguration("/**", config); return new CorsWebFilter(source); }
这样就能解决自定义headers被拦截和跨域问题,但是这样配置紧接着下一个问题又出来了
问题二
由于跨域配置会进行叠加,举个例子你在服务一种添加了跨域配置,在spring cloud Gateway中也添加了,那这样就会产生headers重复的问题:
前端就会报错,
所以你必须要进行header去重,具体办法如下:在spring cloud Gateway的过滤器中添加过滤配置
spring: application: name: nb-web cloud: nacos: discovery: server-addr: localhost:8848 gateway: default-filters: - DedupeResponseHeader=Vary Access-Control-Allow-Credentials Access-Control-Allow-Origin, RETAIN_UNIQUE - DedupeResponseHeader=Access-Control-Allow-Origin, RETAIN_FIRST
这样就能把重复的header给去掉了,spring cloud Gateway过滤器的详细内容可以参考
https://www.imooc.com/article/290816
这样跨域问题基本就能解决了,但是因为我这边需要进行session共享,所以需要给前端传入cookie,那么问题又来了,后端配置的cookie传不出去,原因有两个1:没有加上headers上面加上Access-Control-Allow-Credentials: true,这个可以在
gateway: default-filters: - AddResponseHeader=Access-Control-Allow-Credentials,true
添加上,还有一个就是前端的ajax上没有加上:
, xhrFields: {withCredentials: true} , crossDomain: true
这样浏览器就能保存cookie
至此问题就能解决了。在查阅过程中我看到关于跨域配置重复问题是存在bug的,具体内容可以参考:
https://blog.csdn.net/zimou5581/article/details/90043178
- 点赞
- 收藏
- 分享
- 文章举报
- springcloud项目网关升级:gateway替代zuul以及解决gateway跨域访问问题
- Spring Cloud (6) | spring cloud zuul 跨域问题No 'Access-Control-Allow-Origin' header
- SpringCloud gateway跨域配置
- Spring Boot 处理前端跨域问题
- spring boot 跨域问题处理
- springcloud微服务一:spring boot基础项目搭建及问题处理
- Spring Cloud 学习笔记(六)--Gateway 关于IE跨域的坑及实现
- springcloud gateway代理get正常、post请求报错的问题
- spring利用cors处理跨域问题
- 详解Spring Cloud Finchley版中Consul多实例注册的问题处理
- 通过springcloud-gateway调用后台服务超时的问题
- 问题记录:SpringCloud 灰度环境路由 Gateway
- 详解SpringCloud Finchley Gateway 统一异常处理
- springboot处理ajax请求跨域问题
- 学习-SpringCloudZuul gateway转发静态资源问题
- Spring Cloud Gateway-自定义异常处理
- springcloud跨域问题
- Java spring 框架跨域问题处理
- Spring Cloud Zuul 网关的分布式系统中整合Swagger(转)和 zuul跨域访问问题
- Spring Cloud Gateway -- 获取RequestBody(解决RequestBody不完整的问题)