Last updated: Mar 2, 2024
Reading timeยท2 min
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
keyword (it's case-sensitive).To install the form-data package,
navigate to the root directory of your project (where your package.json
file
is) and run the following command:
# ๐๏ธ if you use NPM npm install form-data # ๐๏ธ if you use YARN yarn add form-data
package.json
file initialized, create one using the npm init -y
command.npm init -y
Now we can import and use the FormData
constructor in our Node.js code. Here's
an example.
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.
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.
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 sample above achieves the same result, however, instead of using ES6
module syntax we used the older require
syntax.
You can check out more examples of using the package in the NPM page of form-data.
If you want to avoid installing a third-party module, use the URLSearchParams class in Node.js.
import fs from 'fs'; const form = new URLSearchParams(); form.append('field', 'my value'); form.append('file', fs.createReadStream('/pictures/avatar.png'));
The URLSearchParams
API provides read and write access to the query of a URL.
If you use the axios
module, you can send a POST request with form data to a
server in the following way.
import axios from 'axios'; const form = new URLSearchParams(); form.append('abc', 'xyz'); form.append('qwe', 'asd'); async function makeRequest() { try { const res = await axios.get('https://example.com', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, data: form, }); const data = res.data; console.log(data); } catch (err) { console.log(err); } } makeRequest();
If you don't have axios installed, make sure to install it first.
# ๐๏ธ if you use NPM npm install axios # ๐๏ธ if you use YARN yarn add axios
You can learn more about the related topics by checking out the following tutorials: