无法让浏览器从express启动下载

4

问题之后,我无法让浏览器从express中下载文件。 后端代码:

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

我已经将文件从.gpx格式更改为文本格式,以确保与此无关,并尝试了如下调整头文件的方法,但无济于事:
res.header('Content-Type', 'text/plain')
res.header('Content-Security-Policy', 'upgrade-insecure-requests');

在前端,我尝试过:

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

并且:

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

并且:

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

我尝试通过GET请求访问后端url(根据我的原始问题的回复),但是没有一个可以在浏览器中启动下载。我认为这是一个前端问题,因为当我在控制台中双击下载时,它会打开。前端正在获取数据,但浏览器(chrome)没有下载它。我还尝试了Firefox,结果相同。有很多类似的查询,但没有一个解决了我的问题。


在浏览器中打开网址 localhost:3000/download 并查看是否下载。如果没有下载,则可能是您的 Express 服务器出了问题,或者请检查开发工具中的网络面板。 - jal
是的,那个可以正常工作。文件会自动下载。问题在于前端 - 我无法让浏览器在代码中启动下载。 - Kissenger
2个回答

3
您代码中的问题在于没有将正确的 url 传递给 window.open。您需要包含 http://。
window.open('http://localhost:3000/download');

哎呀,真是太明显了,我找到它了。谢谢。 - Kissenger

0
出于安全考虑,如果您想下载某些内容,则必须打开新标签页。
因此,请使用


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接