I was faced with the exact same problem last week. The .json
method returns a promise to the JSON, not the JSON itself. If you want to access both the response and the JSON at once, you'll need to use nested closures like this:
fetch(...)
.then(response => {
response.json().then(json => {
// code that can access both here
})
})
Since the callback passed to the json
promise was created within the callback to the fetch
promise, it'll have access to the response
as well.
You might want to make a function that handles JSON and error cases, and then reuse it for all your fetches. For example, something like this:
function fetchHandler(response) {
if (response.ok) {
return response.json().then(json => {
// the status was ok and there is a json body
return Promise.resolve({json: json, response: response});
}).catch(err => {
// the status was ok but there is no json body
return Promise.resolve({response: response});
});
} else {
return response.json().catch(err => {
// the status was not ok and there is no json body
throw new Error(response.statusText);
}).then(json => {
// the status was not ok but there is a json body
throw new Error(json.error.message); // example error message returned by a REST API
});
}
}