0

I have a specific use case where I have to fetch the pdf content using axios.get and then render the content explicitly on UI

On front end I am using React.js and having Express.js server in backend.

My front end React app cannot call cross domain apis (third party apis) so, I have created an endpoint on backend express server which is running on the same domain that eventually deals with third apis, basically fetch pdf content from any third party links.

router.get('/fetch-pdf-content', async (req, res) => {
try {
    const { data } = await axios.get('https://abc.pdf');
    res.contentType('application/pdf');
    res.send(data);
} catch (error) {
    console.error(error);
    res.status(500).send(error.code);
}

})

On front end, how I can render the data I get from server endpoint ?

I tried using object tag on front end like

<object data={'http://localhost:5000/fetch-pdf-content'} type="application/pdf">
<p>Alternative text</p>
</object>

but it does not work. I am able to see object tag in the document but with empty document and Alternative text is not getting displayed.

1 Answers1

0

Axios uses the responseType: 'json' by default, therefore some bytes are interpreted in the wrong way and converted to different values, and the binary data becomes invalid.

E.g. a byte value like 231 is converted to 65533, which is the replacement character "�".

You need to set responseType: 'arraybuffer':

const { data } = await axios.get( url, { responseType: 'arraybuffer' } );
kca
  • 4,856
  • 1
  • 20
  • 41