Solve - FormData is not defined Error in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20211 min read

banner

Photo by Thomas Kelley

Solve - 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're getting the error in the browser, make sure that you have not 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
Note that if your project does not have a package.json file initialized you would have to 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 are using 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee