【问题标题】:Fetch image and send it using koa2获取图像并使用 koa2 发送
【发布时间】:2020-07-04 22:52:10
【问题描述】:

我正在尝试从外部 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
})

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

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

【问题讨论】:

    标签: node.js koa koa2


    【解决方案1】:

    设置responseType: 'stream'。 'arraybuffer' 也可以,但 'stream' 更好,因为你只是通过字节。

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

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

    【讨论】:

      猜你喜欢
      • 2017-03-20
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 2018-12-19
      • 2011-07-05
      • 2013-03-30
      • 1970-01-01
      • 2023-04-10
      相关资源
      最近更新 更多