【发布时间】:2017-07-13 09:49:33
【问题描述】:
我有一个源代码无法访问的服务器,所以我不知道那里发生了什么。
我正在尝试向它发送 CORS 请求,并且请求成功。响应应该有一个 Location 标头,我可以使用 cURL 以及开发工具中的 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 标头?
【问题讨论】:
-
那么,你的状态是2xx?而
console.log('Location:', res.headers.get('Location'));没有记录任何内容? -
@JaromandaX 状态为 201,它打印“位置:空”。
-
您是否看到
Access-Control-Request-Headers: Location标头不在请求标头中 - 它会在预检OPTIONS请求中,老实说,我认为您做错了 CORS - 您想要接收位置,那么为什么要将位置设置为请求标头? -
服务器需要回复
Access-Control-Expose-Headers: Location才能访问它 -
Or, if the response has- 是的,那个 - 你可以安全地删除设置Access-Control-Request-Headers
标签: javascript http-headers cors fetch-api