From 8c3f0d490ba236a8a5ac64f3ad4acee9edfa6620 Mon Sep 17 00:00:00 2001 From: Administrator Date: Tue, 15 Apr 2025 09:52:02 +0800 Subject: [PATCH] =?UTF-8?q?=E8=B7=A8=E5=9F=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/org/hlrj/duobao_demo/tool/CorsConfig.java | 35 ++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/main/java/org/hlrj/duobao_demo/tool/CorsConfig.java 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); + } +}