如何使用 Fetch api 在 CORS 请求中获取 header 字段
How to get header fields in a CORS request using Fetch api
我有一个源代码无法访问的服务器,所以我不知道那里发生了什么。
我正在尝试向它发送 CORS 请求并且请求成功。响应应该有一个 Location header,我可以使用 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"
我需要做什么来提取位置 header?
正如@JaromandaX 指出的那样,服务器响应中缺少 'Access-Control-Expose-Headers': 'Location'
导致无法从响应 object 访问位置 header。必须在服务器中修复它,现在一切正常。
我有一个源代码无法访问的服务器,所以我不知道那里发生了什么。
我正在尝试向它发送 CORS 请求并且请求成功。响应应该有一个 Location header,我可以使用 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"
我需要做什么来提取位置 header?
正如@JaromandaX 指出的那样,服务器响应中缺少 'Access-Control-Expose-Headers': 'Location'
导致无法从响应 object 访问位置 header。必须在服务器中修复它,现在一切正常。