Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

form-data | axios: Unable to get headers from FormData, Error: getHeaders is not a function

I am trying to post text and file fields using form-data and axios, but I am getting an error: getHeaders() is not a function. Below is my submit code, note that I am using React with Typescript.

import * as FormData from 'form-data'
import axios from 'axios'

submit(event: React.FormEvent<HTMLFormElement>) {
  event.preventDefault()

  const { title, description, pictureFile } = this.state

  let data = new FormData()
  data.append('title', title)
  data.append('description', description)
  data.append('picture', pictureFile)

  axios.post('/api/route', data, {
    headers: data.getHeaders() // ERROR: getHeaders is not a function
  })
    .then(res => handle(res))
    .catch(err => handle(err))
}

The particular header I am interested in is the Authorization, I can set it manually, but then the boundaries are required so ... I better try to get that getHeaders() function to work.

I don't get the problem here, getHeaders seems to be part of form-data API.

Please help.

like image 357
acmoune Avatar asked Feb 14 '19 02:02

acmoune


2 Answers

form-data is used only on Node, if you run it on the browser, it will switch to the window's version of FormData. I saw this in their code.

module.exports = typeof self == 'object' ? self.FormData : window.FormData;
like image 156
acmoune Avatar answered Nov 07 '22 09:11

acmoune


I Have faced this issue because I wanted to do some unit testing inside nodejs but my code will be used in browser later on.

Here are two solutions that worked for me:

you can define getHeaders function in FormData class:

declare global {
 interface FormData {
  getHeaders: () => {[key: string]: string};
 }
}

FormData.prototype.getHeaders = () => {
 return { 'Content-Type': 'multipart/form-data' };
};

Or you can just write a ternary statement:

axios.post('/api/route', data, {
    headers: data.getHeaders ? data.getHeaders() : { 'Content-Type': 'multipart/form-data' };
  })
like image 1
Abdel Rahman Avatar answered Nov 07 '22 10:11

Abdel Rahman