Display Pdf in browser using express js

Question

I'm trying to serve a PDF via Express in a way it is displayed in browser:

`app.post('/asset', function(request, response){
  var tempFile="/home/applmgr/Desktop/123456.pdf";
  fs.readFile(tempFile, function (err,data){
     response.contentType("application/pdf");
     response.send(data);
  });
});`

However, the browser shows binary content. How to handle this correctly?

Answer

`post('/fileToSend/', async (req, res) => {

  const documentPath = path.join(
    __dirname,
    '../assets/documents/document.pdf'
  );

  res.setHeader('Content-Type', 'application/pdf');
  res.setHeader('Content-Disposition', 'attachment; filename=document.pdf');

  return res.download(documentPath);
});`

This answer was originally posted on Stack Overflow. You can find the full discussion here

Related Posts

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

## Question Can one transfer repositories from GitLab to GitHub if the need be. If so, how exactly can I go about doing the same? Also, are there any pitfalls in doing so or precautionary measures

Read More

Cannot set headers after they are sent to the client - error

## Question Error `[ERR_HTTP_HEADERS_SENT]`: Cannot set headers after they are sent to the client ```text `at ServerResponse.setHeader (_http_outgoing.js:558:11) at ServerResponse.header (D:\D

Read More

Pulling data with 'Where' and 'Include' statements at the same time

## Question I have managed to get my include statements working with my foreign keys however when I try to add a 'where' statement to the findAll statement I am getting the below error. I have check

Read More