Home > Software design >  Get http response status code after response.json()
Get http response status code after response.json()

Time:02-22

I would like to get http status code after response.json to use it in my logic later, can I do something with it?

function apiRequest(path, options) {
    fetch("api/"   path, options)
        .then(response => response.json())
        .then(data => {
            let res = {
                code: 200 //I want to put http status code here,
                data: data
            }

            return res;
        })
}

CodePudding user response:

As an alternative you could consider async/await. That way you have access to response and data at the same time more easily.

async function apiRequest(path, options) {
    const response = await fetch("api/"   path, options)
    const data = await response.json()

    let res = {
         code: response.status,
         data: data
    }

    // Do something with res
}

CodePudding user response:

Try this

function apiRequest(path, options) {
    fetch("api/"   path, options)
        .then(response => Promise.all([Promise.resolve(response.status), response.json()]))
        .then([status, data] => {
            let res = {
                code: status //I want to put http status code here,
                data: data
            }

            return res;
        })
}

CodePudding user response:

This is slightly tricky using then (as you are currently doing) because you want to get data directly from the response (which is a promise) and some more data from the parsed body (which is another promise).

So you can wrap the status and the data promise in a Promise.all and return that from the first then:

const apiRequest = () => {
  const url = "//swapi.dev/api/planets/1/";
  fetch(url)
    .then((response) => Promise.all([response.status, response.json()]))
    .then(([status, data]) => console.log({status, data}))
}

… but it would be easier to use async/await syntax and ditch the callbacks and you then only have to worry about a single function (and therefore scope) rather than multiple.

const apiRequest = async () => {
  const url = "//swapi.dev/api/planets/1/";
  const response = await fetch(url);
  const data = await response.json();
  const status = response.status;
  console.log({status, data})
}

CodePudding user response:

you can git it in the first then before you return response.json something like this

function apiRequest(path, options) {
  fetch("api/")
    .then((response) => {
      let status = response.status;
      console.log("status", status);
      return response.json();
    })
    .then((data) => {
      console.log(data);
    });
}
apiRequest();

  • Related