【问题标题】:How to get header fields in a CORS request using Fetch api如何使用 Fetch api 获取 CORS 请求中的标头字段
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-20
    • 2018-05-22
    • 2018-03-11
    • 2020-03-12
    • 2021-05-28
    • 2018-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多