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

Angular 14调用getUserInfo报headers.get(...) is null错误求助

问题排查与解决思路

问题还原

Angular 14应用调用后端getUserInfo()接口时,始终抛出TypeError: headers.get(...) is null错误,且浏览器和后端日志均无该请求记录,后端采用Spring Cloud Gateway并已配置CORS。

核心原因分析

该错误多因前端请求头配置不合法,导致浏览器触发的预检请求(OPTIONS)失败,直接拦截了后续业务请求,因此后端完全接收不到请求。

具体解决步骤

1. 移除请求中的Access-Control-Allow-Origin头

Access-Control-Allow-Origin是后端响应头,不属于前端请求头范畴。前端在请求中携带这个头会被浏览器判定为非法请求,直接拦截。修改getUserInfo()方法:

getUserInfo() {
    const httpOptions = {
      headers: new HttpHeaders({
          'Content-Type':  'application/json'
          // 移除Access-Control-Allow-Origin配置
      })
    };
    return this.http.post<any>("http://localhost:8180/auth/userInfo", {}, httpOptions)
        .pipe(map(user => {
            localStorage.setItem('currentUser', JSON.stringify(user));
            this.currentUserSubject.next(user);
            return user;
        }));
}

2. 检查X-Requested-With拦截器的实现

Angular的HttpRequest对象是不可变的,必须通过克隆请求的方式修改请求头,直接修改原对象会导致headers异常。正确的拦截器代码示例:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // 克隆请求并添加X-Requested-With头
    const modifiedRequest = request.clone({
        headers: request.headers.set('X-Requested-With', 'XMLHttpRequest')
    });
    return next.handle(modifiedRequest);
}

3. 验证Spring Cloud Gateway的CORS配置

确保网关配置覆盖预检请求(OPTIONS方法),并允许必要的来源、方法和头:

spring:
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]':
            allowed-origins: "http://localhost:4200"
            allowed-methods: "*"  # 必须包含OPTIONS、POST等方法
            allowed-headers: "*"
            allow-credentials: true
            max-age: 3600  # 预检请求缓存时长,减少重复预检

若网关未正确处理OPTIONS请求,浏览器会拒绝发送后续的POST请求。

4. 排查拦截器冲突

暂时禁用除错误拦截器外的其他拦截器,测试请求是否能正常发送。若禁用后恢复正常,说明是其他拦截器的逻辑导致headers对象损坏。

5. 查看浏览器Network面板

检查Network面板中的OPTIONS请求状态:

  • 若为4xx/5xx,说明网关CORS配置存在问题;
  • 若未出现OPTIONS请求,说明前端请求头的非法配置导致浏览器直接拦截了请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 18:20:25