91

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?

8 Answers 8

120

You can use form-data - npm module.

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'));
Sign up to request clarification or add additional context in comments.

14 Comments

Thanks for your answer. I am working with ES6 so I imported like this:import FormData from 'form-data' But I get error form_data_1.default is not a contructor
If its node js, you only can do var FormData = require('form-data'); Node JS doesn't support ES6 syntaxt for importing.
try import * as FormData from form-data
Thanks. I get another error source.on is not a function. Sorry for my poor question
FormData is a Node API starting with Node 18
|
66

If you only need to submit string values and not Buffer or ReadStream, then URLSearchParams can work for you!

Original Example

var fs = require('fs');
 
var form = new URLSearchParams();
form.append('my_field', 'my value');
form.append('my_second_field', 'my value 2');
form.append('my_third_field', 'my value 3');

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

6 Comments

@OMKARAGRAWAL you should have just edited this one or contributed it here, forking when its not needed just adds to noise. like what was the point
This does not work as described. URLSearchParams only accepts a string as a value, so a ReadStream or Buffer are not valid. Therefore, this is not equivalent to FormData.
This is not going to work if the request is multipart/form-data.
That's totally wrong! URLSearchParams and FormData are two different things and it will not work.
The question is for node.js not for web api
|
43

FormData is now a part of Node 18. They removed the experimental warning they introduced in Node 17: https://github.com/nodejs/node/commit/d33cbabd79

Now you can use it with fetch without any dependencies.

1 Comment

And since v21, it's considered Stable. So this should be the way to go from now to avoid relying on dependencies : nodejs.org/docs/latest/api/globals.html#class-formdata.
10

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

4 Comments

Thanks. Can you let me know how to use that module in ES6 syntax?
import * as FormData from "form-data";
For me this is what worked: import { default as FormData } from "form-data";
@AdelinIonut @DenesTarjan for me it works even simpler import FormData from "form-data";
10

In my opinion the cleanest solution that requires no additional dependencies is:

const formData = new URLSearchParams({
  param1: 'this',
  param2: 'is',
  param3: 'neat',
}) 

Comments

6

I would suggest the npm module formdata-node because it's a complete (spec-compliant) FormData implementation for Node.js. It supports both ESM/CJS targets, so EM6 is supported. You can find a few examples at the npm module page.

Comments

0

node-fetch also exports FormData:

import { FormData } from "node-fetch";

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

Comments

-3
 let _data = new FormData();
_data.append(`FaceDataRecord', '{"faceLibType":"blackFD","FDID":"1","FPID":"${employeeNo}"}`);
_data.append('img', fs.createReadStream('/C:/Users/ALIENWARE/Downloads/unnamed.jpg'));

let _config = {
    method: 'put',
    maxBodyLength: Infinity,
    url: 'http://192.168.1.3/ISAPI/Intelligent/FDLib/FDSetUp?format=json',
    headers: {
        'Accept': '*/*',
        'Accept-Language': 'en-US,en;q=0.9',
        'Connection': 'keep-alive',
        'Cookie': 'language=en; WebSession_F82FED6D22=' + cookie,
        'Origin': 'http://192.168.1.3',
        'Referer': 'http://192.168.1.3/index.asp',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest',
        ..._data.getHeaders()
    },
    data: _data
};

await axios.request(_config)
    .then((response) => {
        console.log(JSON.stringify(response.data));
    })
    .catch((error) => {
        console.log(error);
    });

TypeError: Cannot read property 'name' of undefined

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.