I´m refering to this post: Fetch: POST JSON data
I´ve copied the code which is linked down below.
My question is, is it possible to save for example "Content-Length" which i get as a response in the JSON-file as a variable with which i can continue to work?
Looking forward! Thanks already!
fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 7, str: 'Some string: &=&'})
}).then(res => res.text())
.then(res => console.log(res));
And my result is:
{
"args": {},
"data": "{\"a\":7,\"str\":\"Some string: &=&\"}",
"files": {},
"form": {},
"headers": {
"Accept": "application/json, text/plain, */*",
"Accept-Encoding": "br, gzip, deflate",
"Accept-Language": "*",
"Content-Length": "32",
"Content-Type": "application/json",
"Host": "httpbin.org",
"Sec-Fetch-Mode": "cors",
"User-Agent": "undici",
"X-Amzn-Trace-Id": "Root=1-6388fb1d-3f7791960bdce04f36356182"
},
"json": {
"a": 7,
"str": "Some string: &=&"
},
"origin": "79.208.157.109",
"url": "https://httpbin.org/post"
}
CodePudding user response:
Of course you can - just access it and store it in a variable:
const example = async() => {
const res = await fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 7, str: 'Some string: &=&'})
})
const response = await res.json()
const contentLength = response.headers['Content-Length'];
displayContentLength(contentLength);
}
function displayContentLength(length) {
console.log('The content length is: ' length);
}
example();