91名师指路-头部
91名师指路

spring cloud alibaba 解决跨域问题

由于某些原因,现在不支持支付宝支付,如需要购买源码请加博主微信进行购买,微信号:13248254750

一:代码如下

package com.mszl.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 CorsConfig {

@Bean
public CorsWebFilter corsWebFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedHeader("*"); // 允许任何头
corsConfiguration.addAllowedOriginPattern("*"); // 允许任何域名使用[老版本spring boot 使用AllowedOriginPattern()旧版本使用addAllowedOrigin()]
corsConfiguration.addAllowedMethod("*"); // 允许任何方法(post、get等)
corsConfiguration.setAllowCredentials(true); // 允许cookie
source.registerCorsConfiguration("/**", corsConfiguration); // 对接口配置跨域设置
return new CorsWebFilter(source);
}


}


注意事项:

1)UrlBasedCorsConfigurationSource是import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;包下面的
2)Spring Cloud 使用的是CorsWebFilter,而Spring boot 项目用的是 CorsFilter
3)新版本的Spring boot 采用的是addAllowedOriginPattern,老版本使用的是addAllowedOrigin,我这里使用的spring boot为2.4.2






2022-05-09 16:01:16     阅读(578)

名师出品,必属精品    https://www.91mszl.com

联系博主    
用户登录遮罩层
x

账号登录

91名师指路-底部