在使用前后端分离时,前端请求gateway接口,gateway使用lb负载均衡请求目标服务。
如下:
spring:
cloud:
gateway:
routes:
- id: test-demo
uri: lb://test-demo
predicates:
- Path=/test/**
filters:
- RewritePath=/test/(?.*),/test-demo/$\{segment}
前端请求接口报如下错误:
或
最开始以为仅仅只是跨域问题,尝试了以下方法:
方式一:
在application.yml里配置:
spring:
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]':
allowedOrigins: "*" #这里可以配置固定域名
allowedMethods:
- GET
- POST
参考地址:Spring Cloud Gatewayhttps://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#cors-configuration
此方法似乎缺少什么,仍存在跨域问题,(知道结果的大佬望告知一二)
方式二:
添加配置类,配置跨域:
package com.example.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;
@Configuration
public class ExampleCorsConfiguration {
@Bean
public CorsWebFilter corsWebFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
//1.配置跨域
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedOriginPattern("*");
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsWebFilter(source);
}
}
配置了跨域仍未起效果,搜索文献,发现新版nacos弃用了Ribbon,所以需要添加loadbalancer依赖:
org.springframework.cloud
spring-cloud-loadbalancer
3.1.1
更新依赖,并重启服务,
添加完后就可以正常访问了。
第一个报错应该是依赖问题,第二个报错是跨域问题。
总结:
1.加loadbalancer依赖
2.加跨域配置
3.方式一跨域配置仍存在问题,有知道问题出在哪里的大佬,望指导一二,谢谢。
网上有些资料太老了,与实际问题解决有些出入,调试半天也不起作用,吃一堑长一智。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)