当前端和后端部署在不同的域名下时,会出现跨域问题。Spring Boot 框架提供了一种简单的方式来处理 CORS,允许开发者定义全局的跨域配置。
在 Spring Boot 中,我们可以使用 CorsWebFilter 来全局配置 CORS。
下面是 Spring Boot 中配置 CORS 的示例代码:
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;
import org.springframework.web.util.pattern.PathPatternParser;
import java.util.Arrays;
// 处理跨域的配置类
@Configuration
public class CorsConfig {
@Bean
public CorsWebFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration(); // 创建CORS配置
config.addAllowedMethod("*"); // 允许所有HTTP方法
config.setAllowCredentials(true); // 允许cookies
// @todo 将下面的通配符替换为线上环境的真实域名
config.setAllowedOriginPatterns(Arrays.asList("*")); // 允许所有域名
config.addAllowedHeader("*"); // 允许所有头
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**", config); // 为所有路径注册CORS配置
return new CorsWebFilter(source); // 创建CorsWebFilter
}
}
CORS 配置的优点
今天的代码大赏就到这里。希望通过这篇文章,你能够对 Spring Boot 跨域配置有一个更深入的理解。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有