diff --git a/src/main/java/org/hlrj/duobao_demo/tool/CorsConfig.java b/src/main/java/org/hlrj/duobao_demo/tool/CorsConfig.java new file mode 100644 index 0000000..0dd5ccf --- /dev/null +++ b/src/main/java/org/hlrj/duobao_demo/tool/CorsConfig.java @@ -0,0 +1,35 @@ +package org.hlrj.duobao_demo.tool; + +/** + * @program: duobao_demo + * @ClassName CorsConfig + * @description: 跨域所用到的跨域类 + * @author:liuyusong + * @create: 2025−04-14 19:02 + * @Version 1.0 + **/ + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import org.springframework.web.filter.CorsFilter; + +@Configuration +public class CorsConfig { + + // 当前跨域请求最大有效时长。这里默认1天 + private static final long MAX_AGE = 24 * 60 * 60; + + @Bean + public CorsFilter corsFilter() { + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + CorsConfiguration corsConfiguration = new CorsConfiguration(); + corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址 + corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头 + corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法 + corsConfiguration.setMaxAge(MAX_AGE); + source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置 + return new CorsFilter(source); + } +}