[英]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.