fetch() unexpected end of input

前端 未结 5 2268
暖寄归人
暖寄归人 2020-11-30 02:34

I am using fetch() to grab data from api server. My error looks like this:

Uncaught (in promise) SyntaxError: Unexpected end of input at 
  fetch.then.blob.
         


        
5条回答
  •  星月不相逢
    2020-11-30 02:49

    I had the same problem. in my case it wasn't caused by the response type of 'opaque' as the solution pointed. This code cause an error with empty response, because 'fetch' doesn't accept responses with empty body :

    return fetch(urlToUser, parameters)
    .then(response => {
      return response.json()
    })
    .then((data) => {
      resolve(data)
    })
    .catch((error) => {
      reject(error)
    })
    

    Instead, in my case this works better :

    return fetch(urlToUser, parameters)
    .then(response => {
      return response.text()
    })
    .then((data) => {
      resolve(data ? JSON.parse(data) : {})
    })
    .catch((error) => {
      reject(error)
    })
    

    Gettting the text doesn't give the error even with the empty body. Then check if data exists and resolve. I hope it helps :-)

提交回复
热议问题