我有一个使用ES6 fetch API调用CORS rest端点的react应用程序。fetch调用正常工作,但是我无法获取从服务器发送的响应头。我可以在Chrome开发工具中看到响应头,所以我知道它们正在返回给我;然而在代码中访问它们似乎对我没有用。以下是代码(它是基本的fetch promise-chaining):
fetch(url)
.then(response => {
for (let header of response.headers) { < -- - headers is empty
console.log(header);
}
return response;
});
但是 response.headers 是空的。但我可以在 Chrome 中清楚地看到标题。是否有原因导致 fetch 调用阻止了我查看它们?我需要什么才能访问这些标头?服务器存储一些应用程序特定的标头,我们希望使用它们。
更新:我通过让服务器将此添加到 OPTION 请求的响应中来解决了此问题:
response.setHeader("Access-Control-Expose-Headers", "X-Custom-Header");
现在,在fetch命令的响应中,我可以执行以下操作:
const customHeader = response.headers.get('X-Custom-Header');
感谢Karim提供的帮助!