I'm calling API endpoint using fetch API
.
How can I read response body and headers in resolved body promise?
My code snippet below:
fetch(url, {
credentials: 'include',
method: 'post',
headers: {
"Content-Type": "application/json; charset=utf-8",
},
body: JSON.stringify({
email: email,
password: password,
}),
})
.then(response => response.json())
.then(function(response) {
// How to access response headers here?
});
I'm calling API endpoint using fetch API
.
How can I read response body and headers in resolved body promise?
My code snippet below:
fetch(url, {
credentials: 'include',
method: 'post',
headers: {
"Content-Type": "application/json; charset=utf-8",
},
body: JSON.stringify({
email: email,
password: password,
}),
})
.then(response => response.json())
.then(function(response) {
// How to access response headers here?
});
Share
Improve this question
edited Aug 28, 2023 at 5:56
VLAZ
29.2k9 gold badges63 silver badges84 bronze badges
asked May 22, 2016 at 10:26
LukasMacLukasMac
8981 gold badge8 silver badges20 bronze badges
1 Answer
Reset to default 4As described in the Fetch API documentation, you can get response headers with this snippet:
fetch(myRequest)
.then((response) => {
const contentType = response.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
throw new TypeError("Oops, we haven't got JSON!");
}
return response.json();
})
.then((data) => {
/* process your data further */
})
.catch((error) => console.error(error));
For the body you will find here some examples.