Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use FormData in node.js without Browser?

I want to make a post request in nodejs without browser since it is backend code.

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

But above code gives me error as FormData not defined. I am working with ES6.

Anybody, who can let me know how to use the FormData in nodejs?

like image 606
Adelin Ionut Avatar asked Aug 25 '20 10:08

Adelin Ionut


People also ask

Is formData available in NodeJS?

If its node js, you only can do var FormData = require('form-data'); Node JS doesn't support ES6 syntaxt for importing.

How do I read a formData file?

There is no way to retrieve the files after you've appended them in to a formData-object I believe. You'll have to send the formData-object somewhere and then get the files from a req-object or something like that. The code is taken from : AngularJS: how to implement a simple file upload with multipart form?

How does JavaScript formData work?

The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the fetch() or XMLHttpRequest. send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data" .


3 Answers

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'));
like image 176
Radical Edward Avatar answered Oct 07 '22 10:10

Radical Edward


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
});
like image 42
sudo soul Avatar answered Oct 07 '22 09:10

sudo soul


FormData is a part of JS web API (not included in native NodeJS). You can install the form-data package instead.

like image 8
Daniel Avatar answered Oct 07 '22 09:10

Daniel