admin管理员组

文章数量:1134246

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?

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?

Share Improve this question asked Aug 25, 2020 at 10:32 Josh ThomasJosh Thomas 1,6673 gold badges11 silver badges23 bronze badges
Add a comment  | 

8 Answers 8

Reset to default 116

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

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

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.

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

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

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

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.

node-fetch also exports FormData:

import { FormData } from "node-fetch";

const formdata = new FormData();
formdata.append("chartfile", file);
 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

本文标签: javascriptHow to use FormData in nodejs without BrowserStack Overflow