Axios Network error when generating PDF from Nodejs in a Nextjs application

49 Views Asked by At

I want to generate pdf from Nextjs client using this function:

 const createAndDownloadPdf = () => {
return new Promise(async (resolve, reject) => {
  try {
    const res = await axios.post(`${process.env.NEXT_PUBLIC_API_URL}/create-pdf`, {
      firstName: student?.firstName,
      lastName: student?.lastName,
      matricNumber: student?.matricNumber,
      sex: 'Male'
    }, {
      responseType: 'blob',
    });

    const pdfBlob = new Blob([res.data], { type: 'application/pdf' });
    saveAs(pdfBlob, 'result.pdf');
    resolve();
  } catch (error) {
    reject(error);
  }
});

};

The API that handles the request is as follows;

app.post('/create-pdf', (req, res) => {
pdf.create(pdfTemplate(req.body), {}).toBuffer((err, buffer) => {
  if (err) {
    console.error('Error generating PDF:', err);
    res.status(500).send('Error generating PDF', err);
  } else {
    res.contentType('application/pdf');
    res.send(buffer);
  }
});

});

The problem is that, These codes work in local environment but always returned Network Error in production. I tried deploying to both Heroku and Render and still gets the same problem. Please What could be the cause and how can I fix it?

0

There are 0 best solutions below