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

如何解决Spring Boot部署在AWS HTTPS环境下的CORS跨域问题

问题分析与解决方案

核心问题点

你的CORS配置存在两个关键错误:

  • 路径匹配规则错误:source.registerCorsConfiguration("https://link~~.com", config) 中的第一个参数是用来指定服务器端哪些路径允许跨域,而非前端域名。当前配置只会匹配前端域名对应的路径,服务器实际接口路径根本没被纳入CORS规则,导致跨域校验失败。
  • 潜在的Origin准确性问题:需确保https://link~~.com是前端实际部署的完整HTTPS域名(含非标准端口的话需加上端口),拼写错误或不一致会直接触发CORS拦截。

修复后的完整配置代码

package server.yogoyogu.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        // 替换为前端实际的HTTPS域名,确保拼写完全一致
        config.addAllowedOrigin("https://link~~.com");
        config.addAllowedHeader(CorsConfiguration.ALL);
        config.addAllowedMethod(HttpMethod.GET);
        config.addAllowedMethod(HttpMethod.POST);
        config.addAllowedMethod(HttpMethod.HEAD);
        config.addAllowedMethod(HttpMethod.PUT);
        config.addAllowedMethod(HttpMethod.DELETE);
        config.addAllowedMethod(HttpMethod.TRACE);
        config.addAllowedMethod(HttpMethod.OPTIONS);
        config.setAllowCredentials(true);
        config.setMaxAge(3600L);

        // 关键修改:将路径匹配改为服务器所有接口路径
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

}

额外排查要点

  • 强制清除浏览器缓存:HTTPS启用后,浏览器可能缓存旧的CORS响应头,让前端开发者用Ctrl+Shift+R强制刷新后重试。
  • AWS层面校验:若使用了AWS负载均衡器,检查是否有额外的CORS配置;同时确认安全组是否允许前端域名的请求进入服务器。
  • Origin严格匹配:确保addAllowedOrigin中的域名和前端实际地址完全一致,包括https://前缀,无多余斜杠或空格。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 14:01:06