简体   繁体   中英

How to handle null response in fetch api

I building a react-native app and using fetch api for handling server request, it is working fine if json returned from the server is not null, but if the response from the server is null it will give me an error-"Json Parse error:Unexpected EOF", below is the code used by me for fetch, I tried to set break-point while debugging to see what is coming in response when null is returned from the server, I am unable to find something on which I can put some check and see if response is null before parsing it, so need help

return fetch(url, //service url{
 method: type,     // get or post
  headers: {
   'Accept': 'application/json',
   'Content-Type': contentType,
  },
  body: data    //some input parameters
}).then((response) => {
        return  response.json();
    })
    .then((responseJson) => {
      request.onSuccess(responseJson);   // success callback
    })
    .catch((error) => {
     request.onError(error);     // error callback
      console.error(error);
    });

There is a good answer here , but in my case I needed access to the response object after response.text() returns:

function buildResult(response) {
  // response.json() crashes on null response bodies
  // return {
  //   data: response.json(),
  //   identityToken: response.identityToken // sliding expiration...
  // };

  return new Promise((resolve, reject) => {
    response.text().then(body => {
      resolve({
        data: body.length ? JSON.parse(body) : null,
        identityToken: response.identityToken // sliding expiration...
      });
    }).catch(err => {
      reject(err);
    });
  });
}

//
// the api fetch function
//

function apiFetch(url) {
  return fetch(url)
    .then(checkStatus)
    .then(parseIdentityToken)
    .then(buildResult);
}

If the json response null Instead of using response.json() use response.text()

            fetch(path)
            .then(function (response) {
                return response.text()
            }).then(function (data) {
                resolve(data.length == 0 ? null : JSON.parse(data))
            }).catch(err => {
                reject(err);
            })

If you want to сheck the response request for emptiness :

const response = await fetch(url, options); // your url and options

if (response.ok) {
  const contentType = response.headers.get('content-type');

  if (contentType && contentType.indexOf('application/json') !== -1) {
    const json = await response.json();
    successCb(json); // Write your script.
  } else {
    successCb(); // if the request is successful but the response is empty. Write your script.
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM