Whatwg Fetch fails when json parsing an empty response, how can I prevent it?(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失败,我该如何防止它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:json解析空响应时Whatwg Fetch失败,我该如何防止它?
基础教程推荐
- npm start 错误与 create-react-app 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
