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

Angular 13调用Spring Boot 3接口遇XMLHttpRequest跨域拦截求助

解决方案排查与修复

核心问题分析

登录/注册接口正常但视频列表接口触发CORS错误,结合你的配置来看,大概率是**Angular请求未携带凭证(Credentials)**导致的——因为Spring Boot端已经开启了allowCredentials(true),而浏览器在这种情况下要求请求必须显式声明携带凭证,否则会拦截响应。

修复步骤

修改Angular中VideoService的getAllVideos方法,添加withCredentials: true配置:

export class VideoService {

  private url = "https://localhost:8081/videos/";
  constructor(private httpClient: HttpClient) { }
  
  getAllVideos(): Observable<Array<VideoPayload>>{
    // 添加withCredentials配置
    return this.httpClient.get<Array<VideoPayload>>(this.url + "allVideos", { 
      withCredentials: true 
    });
  }
}

额外排查点

如果上述修复无效,可逐一验证以下内容:

  • 请求URL一致性:确认https://localhost:8081/videos/allVideos与Spring Boot后端的接口映射完全匹配(注意大小写、路径后缀)。
  • 浏览器请求头检查:打开开发者工具(F12)→ Network面板,查看视频列表请求的Request Headers:
    • 确认Origin为http://localhost:4200
    • 确认Cookie字段存在(登录后应携带会话凭证)
  • Spring Boot配置生效验证:检查CORS配置类是否添加了@Configuration和@EnableWebMvc注解,确保配置被Spring正确加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 00:35:06