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

查看:22
本文介绍了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() 将返回一个承诺,所以我事先不知道响应的主体是什么,当主体为空时,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天全站免登陆