Whatwg Fetch fails when json parsing an empty response, how can I prevent it?

醉酒当歌 提交于 2020-01-22 17:22:05

问题


I'm using the Fetch API both in the frontend and on the backend (NodeJS), a problem that I've been facing a lot happens when parsing the response as json.

response.json() will return a promise so I don't know beforehand what the body of the response is, and when the body is empty the JSON parsing will fail with the error:

SyntaxError: Unexpected end of input

So my question is, how to prevent parsing the response when its empty?

Thanks


回答1:


Once you have the Response object, inspect the headers and see what Content-Length says. Based on that you can know whether or not there is something to parse. But also, it seems bogus for the server to return an application/json resource that is empty, as that is not JSON.




回答2:


Since response.json() returns a Promise, You can handle the error with catch and return a dummy data object.

fetch('url').then(response => { 
  return response.json().catch(err => {
    console.error(`'${err}' happened, but no big deal!`);
    return {};
  });
}).then(data => {
  console.log(data); 
});

Update

As mentioned below, if you try to read response twice, you'll get an error: TypeError: Already Read.

As a workaround, it you can clone the original response and call json on the cloned object.

fetch('url').then(response => {
  const responseCopy = response.clone();
  return responseCopy.json().catch(_ => response.text());
}).then(data => {
  console.log(data); 
});



回答3:


Why you don't handle error with try catch

try {
    body = JSON.parse(body)
} catch (err) {

}



回答4:


It is easy, just check response body type like below:

var contentType = response.headers.get('content-type')
        if (contentType && contentType.indexOf('application/json') !== -1) {
            return response.json();
        }else{
            //if response is not json and mostly empty
            return({})
        }

it return empty object if response was null



来源:https://stackoverflow.com/questions/37280029/whatwg-fetch-fails-when-json-parsing-an-empty-response-how-can-i-prevent-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!