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

配置HTTPS的Nginx反向代理下Spring POST请求出现CORS错误求助

解决Nginx反向代理下Spring Boot POST请求CORS错误问题

核心原因及解决步骤

1. 补全Nginx请求头转发配置

POST请求(尤其是带自定义头、JSON数据的场景)会触发OPTIONS预检请求,若Nginx未完整转发请求头,Spring的CORS配置无法识别请求来源,导致错误。

检查并修改Nginx的location配置,确保包含关键转发头:

location / {
    proxy_pass http://127.0.0.1:8080;
    # 必需的转发头
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header Origin $http_origin;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

2. 让Spring Security放行OPTIONS预检请求

若OPTIONS请求被Spring Security拦截,会直接导致CORS失败。在Security配置中添加OPTIONS请求的放行规则:

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    HttpSecurity httpSecurity = http
            .formLogin(form -> form
                    .loginPage(Urls.PUBLIC_LOGIN_PAGE)
                    .permitAll())

            .logout(logout -> logout
                    .logoutUrl("/api/auth/logout")
                    .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK))
                    .invalidateHttpSession(true)
            )
            // 放行所有OPTIONS预检请求
            .authorizeHttpRequests(auth -> auth
                    .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                    .anyRequest().authenticated())

    // 应用CORS配置
    httpSecurity.cors().configurationSource(jpaCorsConfigurationSource);

    return httpSecurity.build();
}

3. 校验Spring CORS配置源规则

确认jpaCorsConfigurationSource的配置覆盖必要规则:

@Bean
CorsConfigurationSource jpaCorsConfigurationSource() {
    CorsConfiguration config = new CorsConfiguration();
    // 生产环境建议指定具体前端域名,而非*
    config.setAllowedOrigins(Arrays.asList("https://your-frontend-domain.com"));
    // 允许的HTTP方法必须包含POST和OPTIONS
    config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
    config.setAllowedHeaders(Arrays.asList("*"));
    // 若前端需携带Cookie/Authorization头,开启此项
    config.setAllowCredentials(true);

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);
    return source;
}

4. 验证预检请求响应

用Chrome开发者工具查看Network面板的OPTIONS请求,确认响应头包含:

  • Access-Control-Allow-Origin:匹配前端域名或*
  • Access-Control-Allow-Methods:包含POST
  • Access-Control-Allow-Headers:覆盖请求携带的所有头(含自定义头)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 22:27:46