JavaScript Fetch API 您可以在 `.then ` 回调中访问 headers 和 JSON 吗?
JavaScript Fetch API can you access headers as well as JSON in a `.then ` callback?
我需要发出 POST 请求,然后根据响应以及 headers,我需要更新保存的状态,我知道 headers 可以通过response.header.get('SOME-KEY')
并且我可以在 .then
回调中访问 JSON 部分响应,如下所示:.then(response => response.json()).then(json =>())
我想知道的是,有没有办法在具有已解析 JSON 响应数据的块中获取两者?
是的,您可以:
.then(response => {
console.log(response.data)
console.log(response.headers)
})
好吧,我不知道我怎么错过了这个,解决方案非常简单,.json()
returns 一个 Promise
,所以我们可以调用 .then
它在当前上下文中并使用 headers 和响应 body:
做我们想做的
fetch('/url')
.then(response => response.json().then(json => ({...json, token: response.headers.get('TOKEN')})))
.then(json => props.updateUser(json));
通过这种方式,我们可以获得所需的 object,其中包含 header 值以及响应数据。 有时候,解决问题只需要睡一觉。
我需要发出 POST 请求,然后根据响应以及 headers,我需要更新保存的状态,我知道 headers 可以通过response.header.get('SOME-KEY')
并且我可以在 .then
回调中访问 JSON 部分响应,如下所示:.then(response => response.json()).then(json =>())
我想知道的是,有没有办法在具有已解析 JSON 响应数据的块中获取两者?
是的,您可以:
.then(response => {
console.log(response.data)
console.log(response.headers)
})
好吧,我不知道我怎么错过了这个,解决方案非常简单,.json()
returns 一个 Promise
,所以我们可以调用 .then
它在当前上下文中并使用 headers 和响应 body:
fetch('/url')
.then(response => response.json().then(json => ({...json, token: response.headers.get('TOKEN')})))
.then(json => props.updateUser(json));
通过这种方式,我们可以获得所需的 object,其中包含 header 值以及响应数据。 有时候,解决问题只需要睡一觉。