README.md 说:
在请求和响应中使用本机流作为正文。
还有sources indicate it supports several types,比如Stream、Buffer、Blob... 并且还会尝试强制转换为String 用于其他类型。
下面的 sn-p 显示了 3 个示例,所有示例都可以使用 v1.7.1 或 2.0.0-alpha5(另请参阅下面的其他示例,FormData):
let fetch = require('node-fetch');
let fs = require('fs');
const stats = fs.statSync("foo.txt");
const fileSizeInBytes = stats.size;
// You can pass any of the 3 objects below as body
let readStream = fs.createReadStream('foo.txt');
//var stringContent = fs.readFileSync('foo.txt', 'utf8');
//var bufferContent = fs.readFileSync('foo.txt');
fetch('http://httpbin.org/post', {
method: 'POST',
headers: {
"Content-length": fileSizeInBytes
},
body: readStream // Here, stringContent or bufferContent would also work
})
.then(function(res) {
return res.json();
}).then(function(json) {
console.log(json);
});
这里是foo.txt:
hello world!
how do you do?
注意:http://httpbin.org/post 回复 JSON,其中包含已发送请求的详细信息。
结果:
{
"args": {},
"data": "hello world!\nhow do you do?\n",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip,deflate",
"Connection": "close",
"Content-Length": "28",
"Host": "httpbin.org",
"User-Agent": "node-fetch/1.0 (+https://github.com/bitinn/node-fetch)"
},
"json": null,
"origin": "86.247.18.156",
"url": "http://httpbin.org/post"
}
如果您需要将文件作为具有更多参数的表单的一部分发送,您可以尝试:
npm install form-data
- 传递一个
FormData对象作为body(FormData是Stream的一种,通过CombinedStreamlibrary)
- 不要在选项中传递
header(与上面的示例不同)
然后就可以了:
const formData = new FormData();
formData.append('file', fs.createReadStream('foo.txt'));
formData.append('blah', 42);
fetch('http://httpbin.org/post', {
method: 'POST',
body: formData
})
结果(只显示发送的内容):
----------------------------802616704485543852140629
Content-Disposition: form-data; name="file"; filename="foo.txt"
Content-Type: text/plain
hello world!
how do you do?
----------------------------802616704485543852140629
Content-Disposition: form-data; name="blah"
42
----------------------------802616704485543852140629--