gpt4 book ai didi

javascript - 使用 https.request 在 nodejs 中发送表单数据

转载 作者:行者123 更新时间:2023-12-03 12:17:36 24 4
gpt4 key购买 nike

我正在尝试将我的 nodejs 服务器的请求发布到另一台服务器,然后我必须将响应保存在文件中。我正在使用 nodejs https.request 模块。

这是我的要求:

    var formData = new FormData();
formData.append('first',3);
formData.append('second', '25');
formData.append('source_file', fs.createReadStream(sourcefile));
formData.append('source_image', fs.createReadStream(sourceimage));

var options = {
hostname: 'ip',
path: '/api/path',
method: 'POST'
}
var file = fs.createWriteStream("file.pdf");
var req = https.request(options, (response) => {
response.pipe(file);
console.log("File saved");
response.send("done")
});

req.on('error', (e) => {
console.error(e);
});

req.write(formData);
req.end();

但我得到了错误
First argument must be a string or Buffer

我尝试使用 formData.toString() 发送我的文件但是在使用它时,错误消失了,但我的文件无法正常工作,而且我已经发送了这样的数据:
 var formData = new FormData();
formData = {
first: 3,
second: '25',
source_file: fs.createReadStream(sourcefile),
source_image: fs.createReadStream(sourceimage)
};

如何使用此请求将我的文件发送到其他服务器。

谢谢

最佳答案

我曾经遇到过类似的问题。我使用 form-data 解决了它NPM 上可用的软件包 hereaxioshere

下面的片段对我有用

const FormData = require("form-data");
const axios = require("axios");

const form = new FormData();
form.append("first", 3);
// other data should go here
form.append("file", fs.createReadStream("filePath"));

axios({
method: "post",
url: "url",
data: form,
headers: { ...form.getHeaders() }
});

关于javascript - 使用 https.request 在 nodejs 中发送表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53588389/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com