如何使用axios nodejs将二进制流从字符串内容发送到第三方api

How to send binary stream from string content to third party api using axios nodejs

我有一个采用二进制文件流的 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?

使用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;