2017-02-23 155 views
0

我有一個源代碼無法訪問的服務器,所以我不知道它在那裏發生了什麼。如何使用Fetch api獲取CORS請求中的頭字段

我想向它發送一個CORS請求,並且請求是成功的。響應應該有一個位置標題,我可以使用cURL以及開發工具中的Firefox網絡監視器選項卡來確認它是否存在。但是我無法使用XMLHttpRequest或者api訪問JavaScript。

我使用fetch API的代碼如下。

fetch(url, { 
    method: 'post', 
    mode: 'cors', 
    credentials: 'include', 
    body: 'creating a new session', 
    headers: { 
    'Access-Control-Request-Headers': 'Location', 
    'Content-Type': 'text/html', 
    }, 
}). 
then((res) => { 
    if (res.status >= 200 && res.status < 300) { 
    console.log('Location:', res.headers.get('Location')); 
    } else { 
    throw new Error('Ooops...something went wrong.'); 
    } 
}) 
.catch(e => console.log(e.message)); 

在Firefox的網絡監視器選項卡中,我得到以下條目。

[Response Headers] 
Access-Control-Allow-Credentials: "true" 
Access-Control-Allow-Origin: "http://localhost:8081" 
Content-Length: <some length> 
Date: <some date> 
Location: <required info is shown> 
Server: <some info> 

[Request Header] 
Host: <host name> 
User Agent: <user agent info for Firefox> 
Accept: <a lot of stuff> 
Accept-Language: "en-US,en;q=0.5" 
Accept-Encoding: "gzip, deflate" 
Content-Type: "text/plain;charset=UTF-8" 
Referer: "http://localhost:8081" 
Origin: <same as Referer> 
Content-Length: "22" 
Authorization: <some string> 
Connection: "keep-alive" 

我需要做些什麼來提取位置標題?

+0

那麼,您的狀態是2xx?和'console.log('Location:',res.headers.get('Location'));'不記錄任何東西? –

+0

@JaromandaX狀態是201,它打印'Location:null'。 –

+0

您是否看到'Access-Control-Request-Headers:Location'標題不在請求標頭中 - 它將出現在「OPTIONS」請求的預檢中,說實話,我認爲你正在做CORS錯誤 - 你想要接收位置,那麼爲什麼你會將位置設置爲請求標題? –

回答

1

正如@JaromandaX指出的那樣,服務器響應中缺少'Access-Control-Expose-Headers': 'Location',導致Location頭部無法從響應對象訪問。必須修復它在服務器,現在一切都完美。

相關問題