无法让浏览器从快递发起下载 [英] Cannot get browser to initiate download from express
问题描述
继续这个问题,我无法让浏览器从快递发起下载。后端代码:
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');
}
});
})
我已经从.gpx文件更改为文本文件,以确保它与此无关,我尝试使用如下所示的标题,但无济于事:
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');
在前端我试过:
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请求导航到后端网址(根据我原来的问题回复),但没有他们在浏览器中启动下载。
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.
我认为这是一个前端问题,因为当我在控制台中双击下载时,它会打开。前端获取数据,但浏览器(chrome)没有下载它。我也试过Firefox,结果相同。
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.
推荐答案
您的代码中的问题是您没有将正确的URL传递给 window.open
。您需要包含 http://
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');
这篇关于无法让浏览器从快递发起下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!