当json解析一个空响应时,Whatwg Fetch失败,如何防止它? [英] Whatwg Fetch fails when json parsing an empty response, how can I prevent it?

查看:140
本文介绍了当json解析一个空响应时,Whatwg Fetch失败,如何防止它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在前端和后端(NodeJS)上都使用Fetch API,将响应解析为json时,我经常遇到的一个问题.

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()将返回一个Promise,因此我事先不知道响应的主体是什么,当主体为空时,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?

谢谢

推荐答案

一旦有了Response对象,请检查标题并查看Content-Length的内容.基于此,您可以知道是否有要解析的内容.但是,服务器返回一个空的application/json资源似乎是伪造的,因为它不是JSON.

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.

这篇关于当json解析一个空响应时,Whatwg Fetch失败,如何防止它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆