You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring REST API配置CORS后未发送CORS Header问题

解决Spring REST API CORS配置不生效的问题

给你梳理几个实际的排查方向和解决办法:

1. 先确认测试方式是否正确

Swagger UI如果和你的API部署在同一个域名下,属于同源请求,这种情况下浏览器不会触发CORS校验,服务器也不会返回CORS相关Header。你得用不同域名的前端页面,或者用Postman模拟跨域请求(手动设置Origin请求头为非当前域名)来测试,才能看到CORS Header是否正常返回。

2. 全局配置里的@EnableWebMvc可能是问题根源

如果你用的是Spring Boot,直接删掉@EnableWebMvc。这个注解会完全禁用Spring Boot的WebMvc自动配置,导致你的CORS配置无法被正确加载。修改后的全局配置类:

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

@Configuration
// 移除@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer{
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOriginPatterns("*") // Spring Boot 2.4+推荐用这个替代allowedOrigins
                .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS")
                .allowedHeaders("*") // 允许所有请求头,避免自定义头被拦截
                .allowCredentials(true); // 需要携带Cookie的话开启这个
    }
}

注意:Spring Boot 2.4及以后版本,allowedOrigins("*")在部分场景下有兼容性问题,官方推荐用allowedOriginPatterns("*")替代。

3. 集成Spring Security时必须额外配置

如果你的项目用了Spring Security,它会优先拦截请求,CORS配置必须和Security整合,否则OPTIONS预检请求会被拦截,导致CORS失效。在Security配置类里添加:

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors() // 开启CORS,自动复用你配置的CorsConfig
            .and()
            .csrf().disable() // 不需要CSRF保护可关闭,按需配置
            .authorizeRequests()
            .antMatchers("/api/**").permitAll(); // 根据实际需求配置权限
    }
}

4. 检查@CrossOrigin的使用细节

如果用注解配置CORS,确保@CrossOrigin放在正确位置:可以在@RestController类上,也可以在具体请求方法上。另外,新版本里注解的origins参数也推荐换成originPatterns:

@RequestMapping("/api/v1/news/articles")
@CrossOrigin(originPatterns = "*") 
@RestController
public class NewsEndpoint {
    // 接口方法
}

最后验证

用Postman发送请求时,手动添加Origin请求头(比如Origin: http://localhost:8081),查看响应头里是否存在Access-Control-Allow-Origin等CORS相关字段,存在则说明配置生效。

内容的提问来源于stack exchange,提问作者Alex_X1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 16:13:31