Fetch 响应中缺少标头

新手上路,请多包涵

我需要做一个 CORS post request 。我需要使用 fetch 因为 axiosresponse 已经处理为 json。

但是在 fetch 响应中, headers 是空的。但我不认为这是服务器问题,因为 axios 响应标头具有我想要的值。

有什么诀窍吗?

     fetch('http://localhost:9876/test/sample-download', {
        method: 'post',
        headers: {},
        body: {}
    })
        .then(response => {
            console.log(response);
        })
        .catch(err => console.error(err));

    axios.post('http://localhost:9876/test/sample-download', {}, {})
        .then(response => console.log(response))
        .catch(error => console.error(error));

原文由 william 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 579
2 个回答

fetch 返回的 Headers 类实例是一个 可迭代的,而不是像 axios 返回的普通对象。某些可迭代的数据,例如 Headers 或 URLSearchParams,无法从控制台查看,您必须迭代它并 console.log 每个元素,例如:

 fetch('http://localhost:9876/test/sample-download', {
    method: 'post',
    headers: {},
    body: {}
})
.then(response => {
  // Inspect the headers in the response
  response.headers.forEach(console.log);
  // OR you can do this
  for(let entry of response.headers.entries()) {
    console.log(entry);
  }
})
.catch(err => console.error(err));

原文由 ccnokes 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题