从 JavaScript 的 fetch 中重新读取响应正文 [英] Reread a response body from JavaScript's fetch
问题描述
fetch()
返回承诺(如果成功)解析为 Response
对象.一个非常常见的做法是立即调用 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:
JSON 中位置 0 的意外标记 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 中).(甚至还有一个只读的 Response.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 解析时,有没有什么方法可以恢复原始响应正文......除了手动读取它(然后转换为 JSON)?
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?
推荐答案
使用 Response.clone()
克隆Response
let clone = response.clone();
或者,使用 Response.body.getReader()
返回一个 ReadableStream
来读取 Response
作为一个流,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屋!