如何使用Fetch api获取CORS请求中的头字段

问题描述:

我有一个源代码无法访问的服务器,所以我不知道它在那里发生了什么。如何使用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错误 - 你想要接收位置,那么为什么你会将位置设置为请求标题? –

正如@JaromandaX指出的那样,服务器响应中缺少'Access-Control-Expose-Headers': 'Location',导致Location头部无法从响应对象访问。必须修复它在服务器,现在一切都完美。