node.jskoakoa2

Fetch image and send it using koa2


I am trying to fetch an image from external URL and then send it as a response in koa2. For fetching the image I am using Axios library.

I am trying to do that the following way:

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
})

But the image I get from that request is not valid. It only shows empty rectangle).

Can someone point me in the right direction on how to resend the received image?


Solution

  • Set responseType: 'stream'. 'arraybuffer' works too, but 'stream' is even better since you're just passing through the bytes.

    By default, I believe axios decodes into a utf-8 string which of course is nonsensical for image binary data.

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