How to use FormData in Node.js without a browser?

I am trying to make a POST request in Node.js backend using FormData:

const formdata = new FormData();
formdata.append('chartfile', file);

However, this results in an error: “FormData is not defined.” I am working with ES6. How can I use FormData in Node.js without relying on the browser?

You can use the popular form-data package to handle form data in Node.js. It is specifically designed to work with multipart/form-data requests.

Steps:

  1. Install the form-data package: npm install form-data

  2. Use it in your code:

const FormData = require('form-data');
const fs = require('fs');
const form = new FormData();

// Append a file (use fs to read the file)

const filePath = './chartfile.png';
form.append('chartfile', fs.createReadStream(filePath));

// You can then use this form object in a POST request

const axios = require('axios');
axios.post('http://example.com/upload', form, {
  headers: form.getHeaders(),
})
.then(response => {
  console.log(response.data);
})
.catch(error => {
  console.error(error);
});

Just to add with @madhurima_sil reply node-fetch allows you to make HTTP requests similar to fetch in the browser. You can also use FormData in combination with node-fetch.

  1. Install the necessary packages: npm install node-fetch form-data

  2. Use FormData with fetch:

const fetch = require('node-fetch');
const FormData = require('form-data');
const fs = require('fs');

const form = new FormData();
const filePath = './chartfile.png';
form.append('chartfile', fs.createReadStream(filePath));

fetch('http://example.com/upload', {
  method: 'POST',
  body: form,
  headers: form.getHeaders(),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

You can also use the axios HTTP client combined with form-data to handle file uploads or form submissions.

  1. Install axios and form-data: npm install axios form-data

  2. Use them together:

const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');

const form = new FormData();
const filePath = './chartfile.png';
form.append('chartfile', fs.createReadStream(filePath));

axios.post('http://example.com/upload', form, {
  headers: form.getHeaders(),
})
.then(response => {
  console.log(response.data);
})
.catch(error => {
  console.error(error);
});