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:
-
Install the form-data package:
npm install form-data
-
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.
-
Install the necessary packages:
npm install node-fetch form-data
-
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.
-
Install axios and form-data:
npm install axios form-data
-
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);
});