获取图像并使用 koa2 发送它

Fetch image and send it using koa2

我正在尝试从外部 URL 获取图像,然后将其作为 koa2 中的响应发送。为了获取图像,我正在使用 Axios 库。

我正在尝试通过以下方式做到这一点:

router.get('/get-image', async (ctx, next) => {
    const {authToken} = ctx.query
    const response = await axiosInstance.get(
        'https://www.someurl.com/image/992',
        {
            headers: {
                Authorization: `Bearer ${authToken}`,
            },
        }
    )

    ctx.type = 'image/jpeg'
    ctx.body = response.data
})

但是我从该请求中获得的图像无效。它只显示空矩形)。

有人可以告诉我如何重新发送收到的图像的正确方向吗?

设置responseType: 'stream'。 'arraybuffer' 也可以,但是 'stream' 更好,因为您只是传递字节。

默认情况下,我认为 axios 解码为 utf-8 字符串,这对于图像二进制数据当然是无意义的。

const response = await axios.get(url, {
  responseType: 'stream',
  ...
})