Muhammad Talha Akram
Muhammad Talha Akram

Reputation: 31

JavaScript Fetch API can you access headers as well as JSON in a `.then ` callback?

I need to make a POST request and then depending on the response as well as the headers, I need to update saved state, I know the headers are available via response.header.get('SOME-KEY') and I can access JSON part of the response in a .then callback like so: .then(response => response.json()).then(json =>())

what I want to know is, is there a way to get both in the block which has the parsed JSON response data?

Upvotes: 2

Views: 1119

Answers (2)

Muhammad Talha Akram
Muhammad Talha Akram

Reputation: 31

Well I don't know how I missed this, the solution was extremely simple, .json() returns a Promise, so we can just call .then on it inside the current context and do what we want with the headers and the response body:

fetch('/url')
  .then(response => response.json().then(json => ({...json, token: response.headers.get('TOKEN')})))
  .then(json => props.updateUser(json));

In this way we can get the desired object which contains the header values as well as the response data. Sometimes all you need to solve your problem is a bit of sleep.

Upvotes: 1

Nikolay Traykov
Nikolay Traykov

Reputation: 1695

Yes, you can:

.then(response => {
    console.log(response.data)
    console.log(response.headers)
})

https://github.com/axios/axios#response-schema

Upvotes: 1

Related Questions