javascript - 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?
解决方案
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.
推荐阅读
- javascript - 使用 Chart.js 时隐藏 xAxis 标签
- python - 如何在python数据透视表数据框中的条形图中添加数据标签值
- python - 为什么隐藏对 dash_html_components.Label 不起作用?
- pandas - Groupby 两列的总和并在熊猫中创建新的数据框
- slurm - 无法在 debian 9 中安装 slurm seff (stretch)
- python-3.7 - 无法通过 pipenv 安装 ccxt.pro - pipenv 需要 #egg 片段来控制版本控制依赖项
- visual-studio-code - Visual Studio Code - 使 Intellisense 完成其他文件中的关键字
- spring-boot - Spring Boot Web 客户端 XML
- javascript - 在 Rails 6 上未定义 Instantclick
- nginx - 使用 kubernetes 秘密使 nginx 可配置?