How to use FormData in Node.js without a 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);
});