Axios error Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream
Asked Answered
H

2

18

I'm getting this error when trying to do a POST request using axios:

Error: Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream at createError

Here's my request:

async function fetchAndHandleErrors() {
  const url = `/claim/${claimId}`;
  const headers = {
    Accept: 'application/json',
    Authorization: `Bearer ${token}`,
  };

  const body = new FormData();
  body.append('damage_description', damageDescription);
  body.append('damaged_phone', {
    uri: imageUri,
    type: 'image/jpeg', // or photo.type
    name: imageUri,
  });

  const result = await axios({
    'post',
    url: `${baseUrl}${url}`,
    data: body,
    headers,
  });
  return result.data;
}

I tried removing result.data and still get the same error. Why is that?

Humpy answered 28/6, 2019 at 8:44 Comment(2)
Any solution for this ?Conspecific
I got this error when using axios to post file in nodeJs. The solution for me was to use Node 18 + fetch built-in functionTorrez
R
3

If you eventually still need a solution for this, I managed to get rid of this error by using the formData.pipe() method. For your case, it could look like this :

import axios from 'axios'
import concat from 'concat-stream'
import fs from 'fs'
import FormData from 'form-data'

async function fetchAndHandleErrors() {
  const file = fs.createReadStream(imageUri)

  let body = new FormData();
  body.append('damage_description', damageDescription);
  body.append('damaged_phone', file);

  body.pipe(concat(data => {    
    const url = `/claim/${claimId}`;
    const headers = {
      'Authorization': `Bearer ${token}`,
      ...body.getHeaders()
    };

    const result = await axios({
      'post',
      url: `${baseUrl}${url}`,
      data: body,
      headers,
    });

    return result.data;
  }))
}

Please let me know if you still encounters your issue, I'll be glad to help !

Revivalism answered 5/1, 2020 at 23:20 Comment(2)
Thank you but there is no body.getHeaders() function on the Axios.FormData function.Sybaris
I just tried but it says formData.pipe is not a function.Affra
C
0

I got this error when I am unnecessarily adding a body to DELETE request.

In my case the object I was using as request body value was null which causes this error.

Since the name of the property for data that I'm attaching to the request is data, the error seems kind of obvious but here I am.

Crossroads answered 4/7, 2024 at 11:23 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.