javascript - 如何将获取响应转换为数组缓冲区?
问题描述
使用像 axios 这样的库,我可以从 http 请求中请求数据作为数组缓冲区:
async function get(url) {
const options = {
method: 'GET',
url: url,
responseType: "arraybuffer"
};
const { data } = await axios(options);
console.log(data)
return data;
}
打印:
<Buffer 50 4b 03 04 14 00 00 00 08 00 3c ef bf bd ef bf bd 52 ef bf bd ef bf bd 3a ef bf bd 46 01 00 00 6f 03 00 00 14 00 00 00 45 43 5f 72 61 77 2f 76 61 72 ... 1740004 more bytes>
假设我没有指定数据作为数组缓冲区进入,或者我使用了一个简单的获取请求:
const response = fetch(url)
如何将其转换response
为数组缓冲区?
我正在尝试这样做:
const response = await this.get(test)
const buffer = Buffer.from(response)
console.log(buffer)
这是打印这个:
<Buffer 50 4b 03 04 14 00 00 00 08 00 3c ef bf bd ef bf bd 52 ef bf bd ef bf bd 3a ef bf bd 46 01 00 00 6f 03 00 00 14 00 00 00 45 43 5f 72 61 77 2f 76 61 72 ... 1740004 more bytes>
解决方案
FetchAPI使用Body Mixins来处理响应正文的处理。
您可能熟悉Body.json,因为 JSON 是解释响应 Body 的最常见方式之一,但也有Body.arrayBuffer
async function get(url) {
const response = await fetch(url);
return response.arrayBuffer();
}
推荐阅读
- c# - ModelState error: The value 'null' is not valid for nullable field
- hibernate - psql 中 ANY 运算符的等效 JPA 查询
- linux - 无法使用 ssh 在 sh 文件上调用带有变量的命令
- php - 加密数据正在更新,但其他正常数据未在 laravel 的数据库中更新
- c - 有没有办法快速找到 Windows 操作系统中的隐藏进程?
- c++ - 模板模板参数和概念
- reactjs - 如何通过axios设置“403 Forbidden”代码响应信息?
- navigation - 后端计算路线,Here-API 仅在地图上显示指导和路线
- windows - 有什么方法可以修复 pgpass.conf 以在 Windows 上正常工作?
- shopify - 如何防止在 Liquid 中舍入数字