json解析空响应时Whatwg Fetch失败,我该如何防止它?

2022-01-20 00:00:00 json node.js fetch javascript

我在前端和后端 (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.

相关文章