How to use FormData in node.js without Browser?
FormData
is a part of JS web API (not included in native NodeJS). You can install the form-data
package instead.
No need for an npm module, URLSearchParams
does the same exact thing!
Original Example
var fs = require('fs');
var form = new URLSearchParams();
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
Axios Example
const formData = new URLSearchParams();
formData.append('field1', 'value1');
formData.append('field2', 'value2');
const response = await axios.request({
url: 'https://example.com',
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: formData
});
You can use form-data - npm module. because formData()
isn't NodeJS API
Use it this way,
var FormData = require('form-data');
var fs = require('fs');
var form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_file', fs.createReadStream('/foo/bar.jpg'));