title: How to forward a file received from an API with Node.js/Express
body: <p><strong>Edit</strong> : not a duplicate of <a href="https://stackoverflow.com/questions/18432779/piping-remote-file-in-expressjs">Piping remote file in ExpressJS</a> . In the referenced question, the distant file is accessible through an url and a <code>GET</code> method. This is not the case here, I am receiving the file in a response payload after a <code>POST</code> request.</p>
  
  <p>I have a frontend that allows the user to download a document. For unrelated reasons, this document is generated by an external service each time the user requests it (based on some contextual data). So the pipeline is like this:</p>
  
  <ol>
  <li>User click link in front end</li>
  <li>Front-end send <code>GET</code> request to back-end</li>
  <li>back-end get relevant internal data and send a <code>POST</code> request to external API</li>
  <li>External API sends a response containing the doc itself, with appropriate <code>content-disposition=attachment</code> and <code>content-type</code> headers, and the document in the body of the response.</li>
  <li>My back-end forwards this to the front-end</li>
  <li>User is prompted with a download link</li>
  </ol>
  
  <p>Steps 1 through 4 work. <strong>What my problem is</strong>:</p>
  
  <ul>
  <li>The user is prompted with a download popup, <strong>the file is of the right type (pdf in my example) but the pdf file is an empty page</strong></li>
  <li>If I send the same request as my backend to the external API but through postman, I get the file I want with the right content.</li>
  <li>If I send the same request as my frontend to the backend but through postman, I get also get an empty pdf file.</li>
  </ul>
  
  <p>My guess is I am not forwarding correctly the response from the external API to the front-end.</p>
  
  <p>My code :</p>
  
  <pre><code>function getDocFromExternalApi(req, res) {
      sendMyRequest().then(externalApiResponse =&gt; {
          res.status(200).header({ //headers appears to be what is expected
              'content-disposition': externalApiResponse.headers['content-disposition'], //= 'attachement; filename="someFileName.pdf"'
              'content-type': externalApiResponse.headers['content-type'] // = 'application/pdf'
          }).send(externalApiResponse.data) //externalApiResponse.data contains the file
      })
  }
  </code></pre>
  
  <p>I also tried adding the charset to <code>content-type</code> and an appropriate <code>content-length</code> header, but no dice either.</p>
  
  <p>The full response from the external API : <a href="https://pastebin.com/5FX72eAX" rel="nofollow noreferrer">https://pastebin.com/5FX72eAX</a></p>