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失败,我该如何防止它?


基础教程推荐
- 如何在特定日期之前获取消息? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01