Skip to content
Advertisement

Get Reponse Code and JSON Response in Fetch

I have following Code to get the Response from the API. Now I want a response if the data are successfully send to the server. My first idea was to do it with the response code. If it is 200 it is successfull. The other idea is, to make it with a try catch statement.

public async daten_eintragen(): Promise<void> {
  // try {
  const headers = {
    "Access-Control-Allow-Origin": "localhost",
    "Access-Control-Allow-Methods": "OPTIONS, GET, POST, PUT, PATCH, DELETE",
  };
  const jsondata = {
    proasdftName: "tfghtdsddskt",
    pauctasdfsion: "this.csdfgudfghrrentItemVersio",
    cosdfasdftName: "mardfddsdfgfdfbvdfdasdfumfghjann",
    vdon: "this.currentItesdfghdfmVersion",
    vedor: "this.currentsdfgItemVendor",
    lde: "this.currentsdfdfgItemFrdgfhamework",
    proepage: "this.csdfgurrentItedfghmHomepage",
    nType: "this.cursdfgrentItedfghmIntegration",
    upe: "this.currentItsdfgfdghemUsage",
    sL: "this.currentItemSsdfgourcfgheCodeAnpassungen",
  };

  console.log(this.currentItemName);

  fetch(this.appConf.apiBaseUrl + "compon", {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify(jsondata),
  }).then(async (response) => {
    // get json response here
    let data = await response.json();

    console.log(data);
  });
}

Getting the response from the server it was successful.

Advertisement

Answer

Looking at the response properties you can simply check response.ok. Something like this:

fetch(this.appConf.apiBaseUrl + "compon", {
  method: "POST",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
  },
  body: JSON.stringify(jsondata),
}).then(async (response) => {
  if (!response.ok) {
    throw new Error(`HTTP error! Status: ${response.status}`);
  }
  console.log("request was successfull. Proceeding with extracting data");
  // get json response here
  let data = await response.json();
  console.log("data", data);
}).catch(e => {
  console.log('An error occurred', e);
});
Advertisement