1

I have 2 Node REST APIs. API A generates a .zip file and sends it as a response (using sendFile()) and API B (gateway) has to retrieve this zip file from API A and send it as a response too (it is kind of nesting the responses).

In order to make this happen, API B uses axios to make the GET request to obtain the .zip. So far I am able to generate this file and download it from API A but I am having trouble handling the download from API B

I read dozens of Stack Overflow questions and in almost every example the client after making a request creates (or receives in responseType) a BLOB object which then gets downloaded to the user. This does not solve this problem because this is not the browser and I need to keep nesting the zip file in the response.

Also, NodeJS does not have blob objects so I don't know if I should get the zip as 'arraybuffer', 'stream' or something else to send it in the response.

exports.getZip = (req, res, next) => {
    axios.get('http://someApi.com', { responseType: 'arraybuffer' })
            .then(response => {
                console.log(response.data); // Buffer Data!
                res.status(201).sendFile(response.data); // ???
            })
}
Runsis
  • 831
  • 9
  • 19

1 Answers1

2

Because you are working between microservices/APIs you cannot receive a blob object or the zip file directly as if this was a browser. One solution is to specify the response type as 'stream' and pipe the data from the response of API A to the response of API B. (could be solved with 'arraybuffer' too but with a different logic)

exports.getZip = (req, res, next) => {
    axios.get('http://someApi.com', { responseType: 'stream' })
            .then(response => {
                // The response will give you the zip file 
                response.data.pipe(res);
            })
}

A similar example can be found on the axios docs

**(A pipe is a mechanism for interprocess communication. Data written to the pipe by one process can be read by another process. The output of a process will be the input of another process Read more about piping here)

Matt
  • 68,711
  • 7
  • 155
  • 158
Runsis
  • 831
  • 9
  • 19