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

使用Ajax调用含Content-Security-Policy头的API时遇CORS问题

CORS问题排查与解决:请求头含Content-Security-Policy导致异常

我用Ajax调用Spring Boot构建的API时遭遇CORS问题,请求头中包含Content-Security-Policy":"frame-ancestors 'none'"。服务器已配置Access-Control-Allow-Origin : *,但移除该Content-Security-Policy头后API可正常工作。

前端请求代码

$.ajax({
    url: "https://****.com/api/v2/login",
    type: 'post',
    data: JSON.stringify(domain),
    headers: {
      "x-dreamfactory-api-key":"*******",
      "x-frame-options":"deny",
      "Content-Security-Policy":"frame-ancestors 'none'",
      "pragma":"no-cache",
      "sec-fetch-mode":"cors",
      "Referer":"https://****.com",
      "origin":"https://****.com",
      "sec-fetch-site":"same-site",
      "sec-fetch-dest":"empty",
      "Content-Type":"application/json"
    },
    dataType: 'json',
    success: function (data) {
        console.log(JSON.stringify(data));
    }
});

Spring Boot API CORS配置

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/v2/**")
            .allowedMethods("PATCH","GET", "POST", "OPTIONS","PUT", "DELETE")
            .allowedOrigins("*")
            .allowedHeaders("*")
            .allowCredentials(true);
} 

解决步骤

  • 移除请求中的安全响应头:Content-Security-Policy和x-frame-options都是服务器返回给浏览器的响应头,用来控制页面安全策略,不需要在请求中携带。直接删掉这两个请求头配置。
  • 修复CORS配置冲突:allowedOrigins("*")和allowCredentials(true)无法同时生效——当允许请求携带凭证(如Cookie、HTTP认证信息)时,Access-Control-Allow-Origin必须指定具体域名,不能用通配符。
    • 如果你的请求需要带凭证,把allowedOrigins("*")改成实际的前端域名,比如allowedOrigins("https://****.com");
    • 如果不需要凭证,直接删除allowCredentials(true)配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 14:32:12