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

Sun*_*arg 6 stream filestream node.js axios

我有一个采用二进制文件流的 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;
Run Code Online (Sandbox Code Playgroud)

但这并不能正确发送数据,因为第三方 API 会抛出异常Bad Request: 400

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

在此输入图像描述

Sun*_*arg 9

使用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;
Run Code Online (Sandbox Code Playgroud)