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
相关产品推荐
相关产品推荐

