how to use FormData in nodejs without browser

编程
Article Directory
  1. 1. detail

how to use FormData in nodejs without browser?

No need for an npm module, URLSearchParams does the same exact thing!

Original Example

1
2
3
4
5
6
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

1
2
3
4
5
6
7
8
9
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
});

detail

需要构造一个表单上传,但是 FormData 似乎只有在浏览器中才能使用

Author: 哒琳

Permalink: http://blog.jieis.cn/2022/fe07fcc1-59c7-411e-8cc7-77a950c6c9e4.html

Comments