首页 > 解决方案 > Ignoring body in a JavaScript fetch response

问题描述

I have some code that wants to issue a request and check whether the request is successful, but it does not care about the response body:

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

As I understand it, the response body is not downloaded yet at this point. If we leave it hanging and don't follow up with something like:

const body = await response.json();

...will the request/response remain open and waiting until perhaps GC occurs? If so, is there a way to cleanly ignore the rest of the response stream without causing issues?

标签: javascripthttpfetch-api

解决方案


You can just do a HEAD if it doesn't have to be a POST and you just want to check if you'll receive a 400 or 500 series error

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.

If you are stuck with a POST request, it's controlled on server-side and you will receive whatever the server returns, there's no web standard that dictates you can tell the server to not send anything, so the server would have to be explicitly written to allow this behaviour.

If you do not care, the GC will run its course once you've exited this particular scope and response is no longer needed. You do not need to await it or anything but it will download in the background (held in memory) and then thrown away when GC runs.


推荐阅读