How to call a file download express middleware function?

Viewed 77

I am learning express and exploring middleware. I am trying to trigger a file download after I hit the root route and send a "Hello World".

So far I have tried.

function download(req, res, next) {
  res.download('FILE/Path/Here');
  next();
}

app.get(req, res, next) => {
  res.send('Hello World')
}

I have also tried.

app.get('/', download, (req, res, next) {
  res.send('Hello World');
}

I Know middleware triggers in order but I cant find a way to have the page render first and then the download prompt.

1 Answers

You cannot send multiple responses to a single http request

However you can send a HTML page containing JavaScript code which makes another request to the download route to bring up the download prompt in the browser as soon as the page is loaded

Related