I'm trying to destructure the response.headers of my axios.get request because I only need the x-csrf-token. It is always the second position. This is the how the res.headers response looks
{
'content-type': 'application/json; charset=utf-8',
'x-csrf-token': '17hoqAWEwVmcN32wYgN9WA==',
'cache-control': 'no-cache, no-store',
dataserviceversion: '2.0',
'c4c-odata-response-time': '1195 ms',
date: 'Fri, 28 Feb 2020 10:06:55 GMT',
'transfer-encoding': 'chunked',
connection: 'close, Transfer-Encoding',
'set-cookie': [
'sap-usercontext=sap-client=041; path=/;HttpOnly;Secure',
'
],
'strict-transport-security': 'max-age=31536000 ; includeSubDomains'
}
I tried
let{a,b} = res.headers;
console.log(b);
and
let[,b] = res.headers;
console.log(b);
But I just get: undefined is not a function
It is always the second position
That doesn't matter with object destructuring. You use the key, not the position.
To get it:
const {'x-csrf-token': token} = res.headers;
or
const {headers: {'x-csrf-token': token}] = res;
Live Example:
const res = {
headers: {
'content-type': 'application/json; charset=utf-8',
'x-csrf-token': '17hoqAWEwVmcN32wYgN9WA==',
'cache-control': 'no-cache, no-store',
dataserviceversion: '2.0',
'c4c-odata-response-time': '1195 ms',
date: 'Fri, 28 Feb 2020 10:06:55 GMT',
'transfer-encoding': 'chunked',
connection: 'close, Transfer-Encoding',
'set-cookie': [
'sap-usercontext=sap-client=041; path=/;HttpOnly;Secure'
],
'strict-transport-security': 'max-age=31536000 ; includeSubDomains'
}
};
const {'x-csrf-token': token} = res.headers;
console.log(token);
const {headers: {'x-csrf-token': token2}} = res;
console.log(token2);
The key here is that destructuring syntax is the converse of an object literal, it's just that instead of key: value
meaning "put value
in for property key
", it means "take the value from property key
and put it in value
" — that is, information in a literal flows right to left, but information in destructuring flows left to right. Here's a figure from Chapter 7 of my new book (see my profile for details);
In this particular case, destructuring doesn't buy you much vs.
const token = res.headers['x-csrf-token'];