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);
});