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.
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;
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' };
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With