[英]Missing headers in Fetch response
我需要发出CORS post request
。 我需要使用fetch
,因为axios
的response
已经处理为 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));
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));
标头仅限于CORS请求。 请参阅https://stackoverflow.com/a/44816592/2047472
(使用access-control-expose-headers
允许将标头暴露给来自不同来源的请求。)
要获取特定标头属性,您可以使用以下内容:
response.headers.get(yourProperty)
另一种选择是使用Object.fromEntries()
,例如Object.fromEntries(response.headers)
或Object.fromEntries(response.headers.entries())
。 此方法将键值对列表转换为 object。
fetch("https://www.google.com").then(response => console.log(Object.fromEntries(response.headers)))
//-> Promise <pending>
// console.log output:
{
"alt-svc": "h3=\":443\"; ma=2592000,h3-29=\":443\"; ma=2592000,h3-T051=\":443\"; ma=2592000,h3-Q050=\":443\"; ma=2592000,h3-Q046=\":443\"; ma=2592000,h3-Q043=\":443\"; ma=2592000,quic=\":443\"; ma=2592000; v=\"46,43\"",
"bfcache-opt-in": "unload",
"cache-control": "private, max-age=0",
"content-encoding": "br",
"content-length": "41556",
"content-security-policy": "upgrade-insecure-requests",
"content-type": "text/html; charset=UTF-8",
"date": "Wed, 04 Aug 2021 08:09:30 GMT",
"expires": "-1",
"server": "gws",
"strict-transport-security": "max-age=31536000",
"x-frame-options": "SAMEORIGIN",
"x-xss-protection": "0"
}
注意:目前 Inte.net Explorer 和 Opera Android 不支持此功能,请参阅MDN 文档上的浏览器兼容性。
虽然正确答案是@AndyTheEntity给我的答案有点不完整。
CORS请求有限制,只显示标题的子集:
Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma
为了在响应上显示更多标头, 服务器必须添加标头以允许更多额外标头。
例如,在POST请求之后,如果创建了新资源,则应返回201 CREATED响应并添加Location
头。 如果您还需要接受CORS,则需要添加下一个标头(在服务器响应上):
Location: $url-of-created-resource
Access-Control-Expose-Headers: Location
有了这个,您将在客户端上看到标题Location
。
如果需要发送特定标头(如SESSION_ID
),则需要在请求中添加下一个标头:
Access-Control-Request-Headers: SESSION_ID
SESSION_ID: $current_session_id
我希望这涵盖所有需要使用CORS处理请求/响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.