Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 506
Chan Jing Hong Avatar asked Jun 28 '19 08:06

Chan Jing Hong


1 Answers

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 !

like image 143
Jackh4l Avatar answered Nov 02 '22 13:11

Jackh4l