首页 > 解决方案 > 如何将获取响应转换为数组缓冲区?

问题描述

使用像 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>

标签: javascriptnode.jsbufferarraybuffer

解决方案


FetchAPI使用Body Mixins来处理响应正文的处理。

您可能熟悉Body.json,因为 JSON 是解释响应 Body 的最常见方式之一,但也有Body.arrayBuffer

async function get(url) {
    const response = await fetch(url);
    return response.arrayBuffer();
}

推荐阅读