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

标签 node.js stream axios filestream

我有一个采用二进制文件流的 API。我可以使用 postman 访问 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

最佳答案

二手 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;

关于node.js - 如何使用 axios nodejs 将二进制流从字符串内容发送到第三方 api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58996278/

相关文章:

azure - 来自本地主机(而非 CLI)的具有 Azure 功能的 CORS

javascript - 如何在 Axios 中处理 net::ERR_CONNECTION_REFUSED - Vue.js

javascript - 在 Try 中调用的 promise 未处理的 promise 拒绝

node.js - 重新说明如何创建过滤器来捕获请求和响应并记录日志

javascript - 使用类验证器和 nestjs 验证嵌套对象

java - char[] 上的流写入器不起作用

node.js - heroku 应用程序因缺少模块而崩溃,但可以在本地主机上运行

C++ 流运算符 << 和操纵器/格式化程序

scala - Scala 中的无限流

javascript - 飞行前响应中的 Access-Control-Allow-Methods 不允许方法 PATCH