I am using the below code in a node express application to fetch a binary file (PDF) and serve it to the browser. However, it's not working! With the below code I seem to see the binary content of the PDF in the browser window, eg
%PDF-1.3 %���� 1 0 obj <> endobj 2 0 obj <> endobj 3 0 obj <> endobj 4 0 obj <> endobj 5 0 obj [ 6 0 R 7 0 R 8 0 R] endobj 6 0 obj <>stream x�+��| endstream endobj 7 0 obj <>stream x�+T0�4�3�P0B.....
The rest call sends a PDF as a application/octet-stream
. Also the same REST endpoint is being used by a React app where the PDF is downloaded correctly (so it's safe to assume the REST call is OK). Any ideas on how I can fix the code?
router.get('/processed/:filename', async (req, res) => {
const { filename } = req.params
console.log(`Fetching file${filename}`)
const file = await axios.get(`http://localhost:8080/files/processed?filename=${filename}.pdf`, {
headers: { Authorization: req.session.token },
})
res.send(file.data)
})
After muchas trial and error, this worked.. so I marked the responseType
as stream
then piped the data to the response
const { filename } = req.params
console.log(`Fetching file${filename}`)
const file = await axios.get(`http://localhost:8080/files/processed?filename=${filename}.pdf`, {
headers: { Authorization: req.session.token },
responseType: 'stream',
})
file.data.pipe(res)