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

前端 未结 4 1508
小鲜肉
小鲜肉 2021-02-12 20:04

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.

respon

4条回答
  •  感动是毒
    2021-02-12 20:28

    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

提交回复
热议问题