6

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);
    });
2
  • 3
    just try/catch that response.json(). if it fails, you know you had a proper response, but not valid JSON, and can reroute accordingly. (the .catch part of the fetch API is not for catching throws, but only for catching true network/request errors) Commented Sep 8, 2016 at 19:48
  • Check this: stackoverflow.com/questions/33237200/… Commented Sep 8, 2016 at 19:55

3 Answers 3

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.
  }
}

Comments

0

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);
            })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.