简体   繁体   English

无法让浏览器从快递发起下载

[英]Cannot get browser to initiate download from express

Following on from this question, I cannot get the browser to initiate a download from express. 这个问题之后,我无法让浏览器从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: 我已经从.gpx文件更改为文本文件以确保它与此无关,我尝试使用如下所示的标题,但无济于事:

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. 并通过GET请求导航到后端URL(根据我原来的问题回复),但没有人在浏览器中启动下载。

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. 前端获取数据,但浏览器(chrome)没有下载它。 I also tried Firefox, same result. 我也试过Firefox,结果相同。

There are many queries similar to this, but none have solved the issue for me. 有许多类似的问题,但没有一个问题解决了我。

The issue in your code is that you are not passing the correct url to window.open . 您的代码中的问题是您没有将正确的URL传递给window.open You need to include http:// 你需要包含http://

window.open('http://localhost:3000/download');

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM