FormData is not defined Error in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

FormData is not defined Error in JavaScript #

The "FormData is not defined Error" error occurs when we try to use the FormData() constructor on the server side, most commonly in a Node.js application. To solve the error, install and import the form-data npm package.

formdata is not defined

If you got the error in the browser, make sure you haven't misspelled the FormData keyword (it's case sensitive).

To install the form-data package, navigate to the root directory of your project and run the following command:

shell
npm install form-data
If your project does not have a package.json file initialized, create one using the npm init -y command.

Now we are able to import and use the FormData constructor in our Node.js code. Here's an example.

index.js
import FormData from 'form-data'; import fs from 'fs'; const form = new FormData(); form.append('field', 'my value'); form.append('file', fs.createReadStream('/pictures/avatar.png')); console.log(form);

We imported the FormData constructor, initialized it, and added 2 fields to it - one that contains a string and one that contains a file stream.

A quick test shows that everything works as expected.

formdata result

We used the ES6 module import/export syntax to import the package. If you use an older version of Node.js, you have to use the require syntax.

index.js
const FormData = require('form-data'); const fs = require('fs'); const form = new FormData(); form.append('field', 'my value'); form.append('file', fs.createReadStream('/pictures/avatar.png')); console.log(form);

The code snippet above achieves the same result, however instead of using ES6 module syntax we used the older require syntax.

Conclusion #

The "FormData is not defined Error" error occurs when we try to use the FormData() constructor on the server side, most commonly in a Node.js application. To solve the error, install and import the form-data npm package.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.