不灭的焱

革命尚未成功,同志仍须努力 下载Java

作者:AlbertWen  添加时间:2026-03-02 16:29:52  修改时间:2026-03-03 00:51:23  分类:07.Java框架/系统  编辑

AI生成的代码,设置API跨域访问:

package com.fuyo.dic.framework.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Web MVC 配置
 *
 * @author AlbertWen
 * @since 2026-03-02
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    /**
     * 配置跨域
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 对所有路径生效
                .allowedOriginPatterns( // 允许的源
                        "http://localhost:*",
                        "http://127.0.0.1:*",
                        "http://192.168.*:*",
                        "http://10.*:*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD") // 允许的HTTP方法
                .allowedHeaders("*") // 允许的请求头
                .exposedHeaders("*")
                .allowCredentials(true) // 是否允许发送Cookie
                .maxAge(3600); // 预检请求的有效期,单位:秒
    }
}

结果总是不起作用,没有在http头信息中返回跨域参数

最后,DeepSeek给出了解决方案:

SpringBoot 3 中跨域配置不起作用通常有以下几个原因和解决方案:

1. Spring Security 冲突问题 🔥

如果你使用了 Spring Security,它会覆盖跨域配置。需要同时在 Security 配置中启用 CORS:

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .cors(cors -> cors.configurationSource(corsConfigurationSource())) // 启用 CORS
            .csrf(csrf -> csrf.disable()) // 根据需要配置
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/**").permitAll() // 根据需要配置
                .anyRequest().authenticated()
            );
        
        return http.build();
    }
    
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList(
            "http://localhost:8080",
            "http://127.0.0.1:8080"
            // 可以添加更多具体地址
        ));
        // 或者使用 allowedOriginPatterns
        configuration.setAllowedOriginPatterns(Arrays.asList(
            "http://localhost:*",
            "http://127.0.0.1:*",
            "http://192.168.*:*",
            "http://10.*:*"
        ));
        
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setExposedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        configuration.setMaxAge(3600L);
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

2. 使用 @Bean 方式配置(替代方案)—— 【备注】最后被采纳的方案

除了 WebMvcConfigurer,还可以使用 @Bean 方式:

package com.fuyo.dic.framework.config;

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;

/**
 * 跨域配置
 *
 * @author AlbertWen
 * @since 2026-03-02
 */
@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedOriginPattern("*");
        corsConfiguration.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }
}

3. 检查配置类是否被扫描

确保你的配置类被 Spring 扫描到:

@Configuration  // 确保有这个注解
public class CorsConfig implements WebMvcConfigurer {
    // 你的跨域配置
}

4. 关于 allowedOriginPatterns 和 allowCredentials

当 allowCredentials(true) 时,不能使用 * 通配符。你的配置是正确的,但需要注意几点:

.allowedOriginPatterns(  // 使用 allowedOriginPatterns 而不是 allowedOrigins
    "http://localhost:[*]",
    "http://127.0.0.1:[*]",
    "http://192.168.*.*:[*]",
    "http://10.*.*:[*]"
)
.allowCredentials(true)  // 允许凭证

5. 调试方法

添加日志查看实际请求头:

# application.yml
logging:
  level:
    org.springframework.web.cors: DEBUG

检查响应头

使用浏览器开发者工具,检查实际响应头是否包含:

  • Access-Control-Allow-Origin

  • Access-Control-Allow-Credentials

  • Access-Control-Allow-Methods

6. 完整示例

结合以上所有点,一个完整的解决方案:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns(
                    "http://localhost:[*]",
                    "http://127.0.0.1:[*]",
                    "http://192.168.*.*:[*]",
                    "http://10.*.*:[*]"
                )
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD")
                .allowedHeaders("Authorization", "Content-Type", "X-Requested-With", 
                              "Accept", "Origin", "Access-Control-Request-Method", 
                              "Access-Control-Request-Headers")
                .exposedHeaders("Access-Control-Allow-Origin", 
                              "Access-Control-Allow-Credentials")
                .allowCredentials(true)
                .maxAge(3600);
    }
}

如果使用了 Spring Security,一定要加上第 1 点的配置,这是最常见的原因。