我正在使用 fetch to wordpress api 发出请求,但我在响应中得到一个空 headers 对象,有人知道为什么吗?
这是我的获取操作
export const getJobs = () => {
return dispatch => {
fetch(endpoints.jobs)
.then(res => res.json())
.then(data => dispatch(setJobs(data)))
}
};
这是我在执行 res.json 之前得到的对象
body: (...)
bodyUsed: false
headers: {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "url"
关于如何从响应中获取所有标头有什么想法吗?
使用 CORS 时访问响应标头存在限制。由于您的响应类型是 cors,这可能是罪魁祸首。
有关详细信息,请参阅this答案。
仅仅因为控制台显示
{}
代表 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)))
}
};
对我来说,这是仪表板和 T.J. 的其他两个答案的组合
在服务器端,我必须将标头
access-control-expose-headers
添加到我的响应中,其中包含我想要读取的以逗号分隔的标头。 请参阅此处有关 access-control-expose-headers
的文档。
但是当我尝试通过
res.headers
访问 console.log(JSON.stringify(res.headers)
时,它只是输出 {}
。 T.J. 的解决方案对我有用,因为我必须使用:
res.headers.get("header-name");
这给了我想要的结果。
尝试使用这个:
response.headers.get('x-auth-token')