24

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.

0

3 Answers 3

23

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; 
Sign up to request clarification or add additional context in comments.

4 Comments

so... how did you get the headers?
I'm also interested ! ... How to get that "boundary" ?
Long time ago, but I think I finally removed the form-data package and managed to add the Auth header using the browser's FormData.
Could you please provide some example code?
3

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

Comments

0

Our solution uses Optional chaining (?.) and Nullish coalescing assignment (??=)). Works both node and browser.

const headers = form.getHeaders?.() ?? { 'Content-Type': 'multipart/form-data' }; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.