DEV Community

Cover image for Forwarding PDFs with Axios
Ahmed Hesham Abdelkader
Ahmed Hesham Abdelkader

Posted on

Forwarding PDFs with Axios

Trying to integrate with an E-commerce platform for a mobile app by sending PDF invoices through a node express app

Axios

So the idea was to fetch the PDF data and return it to the client

The url is not directly used in the client as the E-commerce app requires api-key which is only defined in the server app

const axios = require('axios');
const url = "http://www.africau.edu/images/default/sample.pdf"
axios.defaults.headers.common['Authorization'] = "secret-key";

app.get('/download', async function(req, res) {
   try {
      // Fetch PDF from desired url
      const pdf = await axios.get(url);

      // Set response header to pdf 
      res.setHeader('Content-Type', 'application/pdf');

      // Return PDF data to client
      return res.send(pdf.data);
    } catch (err) {

      // Throw if any error occurred
      return res.status(400).json(err);
    }
});
Enter fullscreen mode Exit fullscreen mode

Testing this endpoint, a blank PDF document response was returned

Going through multiple forms and docs, trying different methods to achieve the same end result

Until I found the answer when I was just giving up where axios have a problem with requesting PDF

Where { responseType: 'arraybuffer' } is provided to axios options api

      await axios.get(url,{responseType:'arraybuffer'});
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
eyupaltindal profile image
eyupaltindal

thanks a lot!
it works.