0

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"
}
VLAZ
  • 26,331
  • 9
  • 49
  • 67

1 Answers1

1

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();
dave
  • 62,300
  • 5
  • 72
  • 93
  • FWIW: it's not necessary to access/parse the body (e.g. `res.json()`) in order to get a header value — just wanted to point out that the tasks are unrelated. – jsejcksn Dec 01 '22 at 19:30
  • Ok thanks, it seems that I´m on the right way with your code! Just one last question, when I´ve got a structure like the following: { "devices": [ { "deviceid": "...", "lastseen": ..., "lowbattery": false, "measurement": { "idx": ..., "ts": ..., } } ], "success": true } I access it like response.devices.measurement['idx'];? Is that correct? – DaveDarell Dec 01 '22 at 19:44
  • It was not 100% correctly from me, I receive the following as a response: { devices: [ { deviceid: '...', lastseen: ..., lowbattery: false, measurement: [Object] } ], success: true } I want to try to access now data which are saved in the [Object] – DaveDarell Dec 01 '22 at 19:49