从JavaScript的fetch中重读响应主体 [英] Reread a response body from JavaScript's fetch
问题描述
fetch()
返回promise(如果成功)解析为 响应
对象。一个非常常见的事情是立即致电 Response.json()
将响应主体转换为JSON对象。
fetch()
returns promise which (if successful) resolves to a Response
object. A very common thing to do is immediately call Response.json()
to convert the response body to a JSON object.
如果响应主体无效JSON ,然后 Response.json()
承诺失败并显示错误。消息是这样的:
If the response body isn't valid JSON, then the Response.json()
promise fails with an error. The message is something along the lines of:
位于0的JSON中的意外标记X
Unexpected token X in JSON at position 0
在尝试诊断问题时,这不是很有用;理想情况下,我希望能够从服务器中看到内容(这通常是一条错误消息)。
That's not very helpful when trying to diagnose the problem; ideally I'd like to be able to see the content from the server (which is often an error message).
但是,您似乎只能在 Response.body
上读取一次流(至少在Chrome中) 。 (甚至还有一个只读的 响应。 bodyUsed
标志。)当 Response.json()
尝试将正文转换为JSON时,已经发生这种情况,因此正文出现在JSON解析失败的情况下永远丢失。
However, it appears that you can only read the stream at Response.body
once (at least in Chrome). (There's even a read-only Response.bodyUsed
flag.) That has already happened when Response.json()
tries to convert the body to JSON, so the body appears to be lost forever in the event of a JSON parsing failure.
有没有办法恢复原始响应体...缺少手动读取它(然后转换到原来的 fetch
Promise结算?
Is there any way to recover the original response body... short of manually reading it (and then converting to JSON) when the original fetch
Promise resolves?
推荐答案
使用< a href =https://developer.mozilla.org/en-US/docs/Web/API/Response/clone =noreferrer> Response.clone()
克隆响应
let clone = response.clone();
或者,使用 Response.body.getReader()
返回 ReadableStream
以读取响应
作为流, TextDecoder()
将 Uint8Array
数据流转换为文本。
Alternatively, use Response.body.getReader()
which returns a ReadableStream
to read Response
as a stream, TextDecoder()
to convert Uint8Array
data stream to text.
这篇关于从JavaScript的fetch中重读响应主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!