忽略 JavaScript 获取响应中的正文

Ignoring body in a JavaScript fetch response

我有一些代码想要发出请求并检查请求是否成功,但它不关心响应体:

async function doTheThing() {
  const response = await fetch(someUrl, { method: 'POST' });
  if (!response.ok) {
    throw new Error(`Request failed with status ${response.status}`);
  }
}

据我了解,目前尚未下载响应 body。如果我们让它悬而未决并且不跟进类似的东西:

const body = await response.json();

...request/response 是否会保持打开状态并等待 GC 发生?如果是这样,有没有办法在不引起问题的情况下完全忽略响应流的其余部分?

will the request/response remain open and waiting until perhaps GC occurs?

简而言之,没有。

const body = await response.json();

指示您的代码等到响应正文下载完毕,它不会触发正文下载。除非有理由不这样做,否则响应主体流将下载内容然后关闭。

您可以在 fetch spec 中阅读有关该过程的信息。

可以在启动后中止提取请求,但由于浏览器支持问题,不建议这样做。参见

如果不必是 POST,您可以只执行 HEAD,您只是想检查是否会收到 400 或 [=13] =] 系列错误

https://developers.google.com/web/ilt/pwa/working-with-the-fetch-api#example_head_requests

Example: HEAD requests By default fetch uses the GET method, which retrieves a specific resource, but other request HTTP methods can also be used.

HEAD requests are just like GET requests except the body of the response is empty. You can use this kind of request when all you want the file's metadata, and you want or need the file's data to be transported.

如果您遇到 POST 请求,它是在服务器端控制的,您将收到服务器 returns 的任何内容,没有网络标准规定您可以告诉服务器不要发送任何内容,因此必须显式写入服务器以允许此行为。

如果您不在意,一旦您退出此特定范围并且不再需要 response,GC 将 运行 它的进程。您不需要 await 它或任何东西,但它会在后台下载(保存在内存中),然后在 GC 运行s 时被丢弃。