如何使用axios nodejs从字符串内容向二进制api发送二进制流

问题描述 投票:0回答:1

我有一个采用二进制文件流的API。我可以使用邮递员访问API。

现在在服务器端,XML的内容位于字符串对象中,因此我首先创建了流,然后使用axios lib(以调用第三方API)将其发布到表单数据中。这就是我的做法]

const Readable = require("stream").Readable;

const stream = new Readable();
stream.push(myXmlContent);
stream.push(null); // the end of the stream

const formData = new FormData();
formData.append("file", stream);

const response = await axios({
    method: "post",
    url: `${this.BASE_URL}/myurl`,
    data: formData
});
return response.data;

但是由于第三方API抛出Bad Request: 400,这不能正确发送数据。

如何将XML字符串内容作为流发送到API?

enter image description here

node.js stream axios filestream
1个回答
0
投票

使用Buffer.from方法发送流。这对我有用

const response = await axios({
    method: "post",
    url: `${this.BASE_URL}/myUrl`,
    data: Buffer.from(myXmlContent),
    headers: { "Content-Type": `application/xml`, }
});

return response.data;
© www.soinside.com 2019 - 2024. All rights reserved.