如何使用Content-Type标头创建响应?

问题描述 投票:1回答:1

为了测试项目中的fetch调用,我进行了一些模拟,拦截请求并建立了自己的Response对象。

由于返回的数据是JSON,我想在响应中添加Content-Type标头,并在客户端上进行检查,并选择documented as valid on mozdev,但是在Chrome或Firefox中,创建的Response具有一个空的headers属性。

const response = new Response(myData, {
  status: 200,
  statusText: 'OK',
  headers: {
    'Content-Type': 'application/json'
  }
}

当然,我也尝试插入新创建的Headers对象。我得到了相同的结果。

Here is the result on Chrome

我做错了吗?

javascript mocking fetch content-type response-headers
1个回答
0
投票

这仅仅是因为Headers不是普通的对象(所以devtools不知道如何扩展它)。参见https://developer.mozilla.org/en-US/docs/Web/API/Headers

您可以在其上调用keys()entries()以查看其中的内容。

或更具体而言,response.headers.get('Content-Type')将显示application/json

© www.soinside.com 2019 - 2024. All rights reserved.