Search code examples
node.jsstreamaxiosfilestream

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


I have an API that takes a binary file stream. I am able to hit the API using postman.

Now on the server-side, the content of XML is in string object, So I have created stream first then posted it using axios lib (to call third party API) with form data. This is how I am doing

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;

but this is not sending data properly as third party API throws Bad Request: 400.

How can I send XML string content to API as a stream?

enter image description here


Solution

  • Used Buffer.from method to send the stream. This worked for me

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