解决springcloud gateway 3.X跨域问题

本文介绍了在遇到SpringCloud Gateway 3.x跨域问题时,如何通过错误提示解决配置问题,提供了具体的代码修改建议,帮助读者成功处理跨域请求。
摘要由CSDN通过智能技术生成

我之前报的错误:

When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.

网上有很多解决手法,都差不多,只需加这段代码:

List<String> allowedOriginPatterns = new ArrayList<>();
allowedOriginPatterns.add("*");
corsConfiguration.setAllowedOriginPatterns(allowedOriginPatterns);

没有用,我仔细阅读报的错误,其实已经告诉我了,是要这样改:

corsConfiguration.setAllowCredentials ( true );

       改:

corsConfiguration.setAllowCredentials ( false );

完整的代理是这样的:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfigurat
对于Spring Cloud Gateway跨域问题,你可以通过以下步骤解决: 1. 在你的Spring Cloud Gateway项目中,创建一个全局的跨域配置类,比如命名为CorsConfig。 2. 在CorsConfig类上添加注解`@Configuration`,使其成为一个配置类。 3. 在CorsConfig类中添加一个方法来配置跨域规则,比如命名为addCorsMappings。 4. 在addCorsMappings方法上添加注解`@Bean`,使其成为一个Bean。 5. 在addCorsMappings方法中使用CorsRegistry对象来配置跨域规则。例如: ```java @Configuration public class CorsConfig { @Bean public WebFluxConfigurer corsConfigurer() { return new WebFluxConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("*") .allowedHeaders("*") .exposedHeaders("Authorization") .allowCredentials(true) .maxAge(3600); } }; } } ``` 在上述示例中,通过调用CorsRegistry对象的addMapping方法来添加跨域规则。其中,allowedOrigins设置允许的源(域)地址,allowedMethods设置允许的HTTP方法,allowedHeaders设置允许的请求头,exposedHeaders设置允许暴露的响应头,allowCredentials设置是否允许发送cookie信息,maxAge设置预检请求的缓存时间。 这样配置后,Spring Cloud Gateway就会支持跨域请求了。注意,如果你使用的是WebFlux框架,需要返回WebFluxConfigurer对象并重写addCorsMappings方法;如果使用的是WebMvc框架,则需要返回WebMvcConfigurer对象并重写addCorsMappings方法。 希望以上信息对你有所帮助!如有更多问题,请继续提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值