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

如何Mock支持POST/GET请求的Interceptor?解决headers.get报错问题

问题解决:TypeError: req.headers.get is not a function

问题根源

你遇到的错误是因为直接把普通JS对象传给了HttpRequest或HttpResponse的headers参数,而Angular的HttpRequest/HttpResponse要求headers必须是HttpHeaders实例,普通对象没有get()方法,所以触发报错。

修复步骤

1. 导入HttpHeaders

确保测试文件顶部导入该类:

import { HttpHeaders } from '@angular/common/http';

2. 修正POST请求的HttpRequest创建

把POST分支里的普通对象headers替换为HttpHeaders实例:

switch (e.req_type) {
  case 'GET':
    mockRequest = new HttpRequest('GET', mockUrl);
    break;
  case 'POST':
    // 用HttpHeaders包裹普通对象,生成合法的请求头实例
    mockRequest = new HttpRequest(
      'POST',
      mockUrl,
      {},
      { headers: new HttpHeaders(e.input) }
    );
    break;
}

3. 修正HttpResponse的headers参数

无论在handleNext的伪造实现还是mock HttpHandler的handle方法里,创建HttpResponse时都要把普通对象转为HttpHeaders实例:

// 修正handleNext中的POST响应
if (req.method === 'POST') {
  response = new HttpResponse({
    status: 200,
    body: {},
    url: req.url,
    headers: new HttpHeaders(e.output)
  });
}

// 修正mock HttpHandler中的POST响应
if (_req.method === 'POST') {
  return of(
    new HttpResponse({
      status: 500,
      body: {},
      url: _req.url,
      headers: new HttpHeaders(e.output)
    })
  );
}

补充说明

Angular的HttpHeaders会自动处理普通对象的键值对,生成符合HTTP规范的请求头实例,只有这类实例才拥有get()、has()等方法。之前GET请求正常是因为没传自定义headers,Angular自动生成了空的HttpHeaders实例;而POST请求传了普通对象,导致headers类型不匹配,触发错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 08:35:29