fetch icon indicating copy to clipboard operation
fetch copied to clipboard

response.json() gives an error "unexpected end of input" if the data sent back from request is null.

Open andreacab opened this issue 10 years ago • 11 comments

This is what I have:

this.authTokenStore.get()
    .then(authToken => {
        return fetch(this.serverUrl + '/REST/search?searchTerms=' + text, {
            method: 'get',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'X-Client-Auth-Token': authToken
            }
        })
    })
    .then(this._checkStatus)
    .then(this._parseJSON)
    .then(serverGetSearchSuccess)
    .catch(serverGetSearchError);

What I don't understand and would need some help, it is with the fact that the response has a status 200, then goes to parseJSON but then goes back to checkStatus and throws that error "unexpected end of input" (debugging step by step using the chrome debugger).

My question I guess is how could I check for the body of the request in the this._parseJSON function and detect there if it is null and do a return Promise.resolve(response) instead of response.json()

I am not sure if that should be posted on some site like SO, if yes I'm sorry for the inconvenience.

Thx for your help

andreacab avatar Jan 29 '16 02:01 andreacab

This is a usage question and as such should be asked on sites like SO instead of here.

Ideally, the server shouldn't return an invalid (empty) response body to an application/json request, especially because it responded with HTTP 200. But since it misbehaves, you can catch those occurrences inside .catch(serverGetSearchError). I'm not sure why would you want to resolve a promise in that case, like nothing bad happened.

But if you want to avoid a parse error at all costs, why can't you change your _parseJSON function?

_parseJSON: function(response) {
  return response.text().then(function(text) {
    return text ? JSON.parse(text) : {}
  })
}

In any case, the power is in your hands. We can't decide your app's logic for you.

mislav avatar Jan 29 '16 02:01 mislav

Hey Mislav, thanks for your response and thanks for the work on the fetch polyfill, it's been a real help. Sorry again for posting that here.

andreacab avatar Jan 29 '16 05:01 andreacab

This is a super late response, but anyways my 2 cents on this issue is that if you're expecting a null response body, with a status code of > 200, you can always send a 204 (no content) response back from the server and handle it without the use of response.json() call.

abologna-r7 avatar Feb 01 '17 20:02 abologna-r7

@mislav it's nice , and i think maybe add one step to verify that text will be better.

// https://github.com/douglascrockford/JSON-js/blob/master/json2.js#478
const rxOne = /^[\],:{}\s]*$/;
const rxTwo = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
const rxThree = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
const rxFour = /(?:^|:|,)(?:\s*\[)+/g;
const isJSON = (input) => (
  input.length && rxOne.test(
    input.replace(rxTwo, '@')
      .replace(rxThree, ']')
      .replace(rxFour, '')
  )
);

_parseJSON: function(response) {
  return response.text().then(function(text) {
    return isJSON(text) ? JSON.parse(text) : {}
  })
}

tonyc726 avatar Apr 12 '17 09:04 tonyc726

@mislav the solution almost works, it is enough to do it like this:

_parseJSON(response) { return response.text() ? JSON.parse(response) : null }

Your version was crashing on my side.

Zoly90 avatar May 18 '17 07:05 Zoly90

I also encountered a similar problem, read the above method, still can not be solved, this is my code http://ww1.sinaimg.cn/large/005SjUnYly1flgt8vhksfj30sy0cpabd.jpg @andreacab

HelloAndyZhang avatar Nov 13 '17 14:11 HelloAndyZhang

@Zoly90 and @AndyZhang7

The solution from @mislav works as expected. It's important to note that if you are using the _parseJSON function/JSON.parse will trow an exemption whenever it tries to parse an invalid JSON text. For instance, if you are using the _parseJSON within a Promise chain with a .catch handler, that handler will catch the Parsing exemption.

ysfdev avatar Feb 27 '18 19:02 ysfdev

this error maybe server not allowed, if CORS set moda:cors in request, and check error message if let u set no-cors, then u need teel backend let u address request, worth checking if anyone else.

ruoru avatar May 24 '18 09:05 ruoru

I use this code

tryGetJson = async (resp) => {
    return new Promise((resolve) => {
      if (resp) {
        resp.json().then(json => resolve(json)).catch(() => resolve(null))
      } else {
        resolve(null)
      }
    })
  }

antoxi4 avatar Jun 22 '18 16:06 antoxi4

@antoxi4 sometime is not ur code problem. and whatever use ES5 or ES6.

ruoru avatar Jun 25 '18 01:06 ruoru

@antoxi4 By using catch on resp.json() - you might be silently suppressing genuine parsing errors too. So when there is no data or when data has parsing errors - your code always assumes only no data case

kvr2277 avatar Jul 06 '18 13:07 kvr2277