我有一个服务器,其源代码无法访问,所以我不知道它在那里发生了什么。
我正在尝试向其发送CORS请求,请求成功。响应应该有一个Location标头,我可以使用cURL以及Dev Tools中的Firefox网络监视器选项卡确认它是否存在。但我无法使用XMLHttpRequest或fetch 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"
提取Location标头需要做什么?
答案 0 :(得分:1)
正如@JaromandaX指出的那样,服务器响应中缺少'Access-Control-Expose-Headers': 'Location'
导致无法从响应对象访问Location标头。不得不在服务器中修复它,现在一切都运行良好。