4

Following on from this question, I cannot get the browser to initiate a download from express. Backend code:

app.get('/download', (req, res) => {
  res.download('./textfile.txt', (err) => {
    if (err) {
      console.log('error: ' + err);
    }   else {
      console.log('success');
    }
  });
})

I have changed from a .gpx file to text file to ensure its nothing to do with that, and I have tried playing with the headers as below, to no avail:

res.header('Content-Type', 'text/plain')
res.header('Content-Security-Policy', 'upgrade-insecure-requests');

On the front-end I have tried:

window.location.href = 'localhost:3000/download';

and:

const filePath = 'localhost:3000/download';
const link = document.createElement('a');
link.href = filePath;
link.download = filePath.substr(filePath.lastIndexOf('/') + 1);
link.click();

and:

const newWindow = window.open('localhost:3000/download', 'download');

and navigating to the backend url via GET request (per response to my original question), but none of them initiate the download in the browser.

I think it is a front-end problem, as when I double-click on the download in the console, it opens. The front end is getting the data, but the browser (chrome) is not downloading it. I also tried Firefox, same result.

There are many queries similar to this, but none have solved the issue for me.

Kissenger
  • 345
  • 4
  • 15
  • Open the url `localhost:3000/download` in your browser and see if it downloads. If not then your express server is the issue or check the network panel in dev tools. – jal Jan 05 '19 at 16:31
  • yes, that works without issue. File auto-downloads. The issue is I think with the front-end - I cannot get the browser to initiate the download in the code. – Kissenger Jan 05 '19 at 17:04

2 Answers2

3

The issue in your code is that you are not passing the correct url to window.open. You need to include http://

window.open('http://localhost:3000/download');
jal
  • 1,100
  • 1
  • 8
  • 17
0

For security purpose it is said that you have to open new tab if you want to download something.
So use

window.open('http://localhost:3000/download','_blank')
Rajan Lagah
  • 2,373
  • 1
  • 24
  • 40