2

I am trying to preview an image in my react application. I am trying to use node-fetch to fetch the binary data as stream and upon response, send the response data back to react application with proper content-type. The react code works fine as I tested it already by hitting the API directly. I tried the below code but unable to understand how to configure the response to send binary data.

  fetch(doc_preview_url, requestOptions)
    .then((response) => {
      res.setHeader("Content-Type", response.headers.get('content-type'));
      res.send(response.status).send(response.buffer());
    })
    .catch((error) => {
      errorHandler(error);
    });

Please note I tried this with axios in Node.js but while axios is working fine for PDFs its failing for images(corrupting the binary data). With the above code I am receiving binary data but the data seems to be corrupted as well. When I try to create a objectUrl in react using the same it does not show the correct file in browser.

Jyotirmoy Pan
  • 837
  • 2
  • 10
  • 28

1 Answers1

3

Use the response.buffer() a a promise instead and on finish send the response. The issue with my code was that I was sending the data before it could complete fetching the data.

  fetch(doc_preview_url, requestOptions)
    .then((response) => {
      const contentType = response.headers.get("content-type");
      response.buffer().then((buffer) => {
        res.setHeader("Content-Type", contentType);
        res.status(200).send(buffer);
      });
    })
    .catch((error) => {
      global.logger.logMethodExecutionTime(
        "documentServices.previewDocument ended with error",
        hrstart
      );
Jyotirmoy Pan
  • 837
  • 2
  • 10
  • 28