Search code examples
javascriptreactjsexpresspdfreact-context

Blank content is displayed when trying to open .pdf in another tab using React and Express


I am trying to open a .pdf in another tab that is stored in the server's file system (I am using Express, React and MySQL). When the user clicks the "See" button, the displayCV function is executed, and a new tab is open, but the .pdf content is blank even though the new tab shows the correct number of pages the .pdf contains.

The flow goes like this:

JobItem.jsx

const displayCV = async (e) => {
   e.preventDefault();
   await displayCurriculum();
};

JobContext.js

const displayCurriculum = async () => {
  const { id } = params;

  const response = await axios.get(`/api/jobs/${id}/cv`);
  // console.log(response);

  const file = new Blob([response.data], {
    type: "application/pdf",
  });

  const fileURL = URL.createObjectURL(file);
  const pdfWindow = window.open();
  pdfWindow.location.href = fileURL;
};

The backend looks like this:

jobRoutes.js

const express = require("express");
const router = express.Router();
const { displayCurriculum } = require("../controllers/jobController");
router.route("/:id/cv").get(displayCurriculum);

jobController.js

const displayCurriculum = asyncHandler(async (req, res) => {
  try {
    const { id } = req.params,
      q = `SELECT curriculum FROM jobs WHERE idjobs = ?`,
      doc = await pool.query(q, [id]);

    const fileName = doc[0].curriculum;

    // const data = fs.readFileSync(filesPath + "\\" + fileName);
    res.setHeader("Content-Type", "application/pdf");
    res.sendFile(fileName, { root: filesPath }, (err) => {
      if (err) console.log(err);
      else console.log("Sent: ", fileName);
    });
  } catch (error) {
    console.log(error);
  }
});

If I use Postman and hit the API's endpoint (/api/jobs/${id}/cv) the .pdf is displayed correctly in Postman. When hitting the endpoint from the frontend I get the following Image with blank .pdf content

How can I display the .pdf content in the new tab?


Solution

  • In this case, it turns out that the responseType from Axios needs to be set to "blob" for the .pdf to be read.

    JobContext.js

     const displayCurriculum = async () => {
        const { id } = params;
        const response = await axios.get(`/api/jobs/${id}/cv`, {
          method: "GET",
          responseType: "blob",
        });
    
        const file = new Blob([response.data], {
          type: "application/pdf",
        });
    
        const fileURL = URL.createObjectURL(file);
        window.open(fileURL);
     };
    

    The .pdf is now opening in a new tab and is showing its content. However, the name of the file in the URL is set to the DOMString that is created by URL.createObjectURL(). If the user tries to download the .pdf, the default filename will be the DOMString generated.

    Example URL:

    blob:http://localhost:3000/c6430bc7-99b3-4dae-9caf-79997f801752