Hey I´m getting this response query a API with node fetch:
{
'access-control-allow-credentials': 'true',
'access-control-allow-headers': 'Origin, Content-Type, Accept, Authorization, X-Request-With, Webpunch-App-Version, X-timezone, X-token',
'access-control-allow-methods': 'POST, GET, OPTIONS, PUT, DELETE',
'access-control-allow-origin': 'censored',
'access-control-max-age': '86400',
'cache-control': [ 'no-store, no-cache, must-revalidate', 'no-cache, private' ],
'content-encoding': 'gzip',
'content-type': 'application/json',
date: 'Sun, 29 May 2022 13:04:49 GMT',
expires: 'Thu, 19 Nov 1981 08:52:00 GMT',
pragma: 'no-cache',
'set-cookie': [
'QWFMSESSION=censored; path=/; secure; HttpOnly',
'api_session=meJMkISigaS2dcHK7kKBzFjWyY4zHiQHnyKOiix4; expires=Sun, 05-Jun-2022 13:04:49 GMT; Max-Age=604800; path=/; secure; httponly; samesite=lax'
],
'strict-transport-security': 'max-age=15724800; includeSubdomains; preload',
'transfer-encoding': 'chunked',
vary: 'Accept-Encoding',
'x-content-type-options': 'nosniff',
'x-frame-options': 'SAMEORIGIN',
'x-xss-protection': '1; mode=block'
}
And want to get the 'api_session' token value. When I try to use result['set-cookie']
it returns undefined. When i try use JSON.parse(JSON.stringify(result))
it returns a blank array. But when i copy the result and paste it to another js file it works without any problems... here´s my code:
fetch('censored', {
method: 'POST',
headers: {
censored
},
body: censored
})
.then(async (res) => {
return [await res.json(), res.headers];
})
.then(([jsonData, result]) => {
console.log(result['set-cookie'])
})
.catch((err) => {
// handle error
console.error(err);
});
CodePudding user response:
fetch('')
.then(async (res) => {
return [await res.json(), res.headers];
})
.then(([jsonData, result]) => {
console.log(jsonData['set-cookie'])
})
.catch((err) => {
// handle error
console.error(err);
});
You need to read from jsonData
and not from result
Result сontain request headers
If you wanna get api-session
from header try this
fetch('')
.then(async (res) => {
return [await res.json(), res.headers];
})
.then(([jsonData, result]) => {
console.log(result.get('api_session'))
})
.catch((err) => {
// handle error
console.error(err);
});
CodePudding user response:
response.headers is an instance of the Headers constructor, and properties of a Header instance are protected that's why you can't access them using dot notation or brackets notation example:
fetch(url).then(function(response) {
console.log(response.headers); //Headers {} (you will get an empty object)
});
that's why you should use the get
method to access headers properties, but I think using the Spread operator may also
example:
fetch(url).then(function(response) {
console.log([...response.headers]);
});
read more about the header constructor here https://developer.mozilla.org/en-US/docs/Web/API/Headers/Headers