Cannot get browser to initiate download from express

馋奶兔 提交于 2020-01-04 02:28:06

问题


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.


回答1:


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');



回答2:


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')


来源:https://stackoverflow.com/questions/54053901/cannot-get-browser-to-initiate-download-from-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!