JS 获取,没有在响应中获取标头

Jor*_*uez 6 javascript wordpress fetch

我正在使用 fetch to wordpress api 发出请求,但我在响应中得到一个空的 headers 对象,有人知道为什么吗?

这是我的提取操作

export const getJobs = () => {
  return dispatch => {
    fetch(endpoints.jobs)
      .then(res => res.json())
      .then(data => dispatch(setJobs(data)))
  }
};
Run Code Online (Sandbox Code Playgroud)

这是我在做 res.json 之前得到的对象

body: (...)
bodyUsed: false
headers: {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "url"
Run Code Online (Sandbox Code Playgroud)

关于如何从响应中获取所有标题的任何想法?

T.J*_*der 5

仅仅因为控制台显示{}for headers,并不一定意味着没有任何可访问的标头。如果发送了任何内容,它们应该可以在 上访问res.headers,这是一个Headers对象,...

...允许您对 HTTP 请求和响应标头执行各种操作。

...例如,与get.

例如,如果setJobs需要foo标题:

export const getJobs = () => {
  return dispatch => {
    fetch(endpoints.jobs)
      // Read and parse the body and then return an object with the body data and the `foo` header
      .then(res => res.json().then(data => ({data, foo: res.headers.get("foo")})))
      // Receive the body data and the `foo` header and pass them on to `setJobs`
      .then(({data, foo}) => dispatch(setJobs(data, foo)))
  }
};
Run Code Online (Sandbox Code Playgroud)


ale*_*ria 5

使用 CORS 时访问响应头有限制。由于您的响应类型是 cors,这可能是罪魁祸首。

有关详细信息,请参阅答案。