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

1

6

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

Dextroamphetamine answered 22/11, 2019 at 14:27 Comment(2)
Not sure, but IIRC, this could do the trick : headers: { 'Content-Type': `multipart/form-data; boundary=${formData._boundary}`, }Flutist
Tried not working.. :(Dextroamphetamine
D
9

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;
Dextroamphetamine answered 25/11, 2019 at 12:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.