从 this 开始问题,我无法让浏览器启动从 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,同样的结果。
有很多类似的查询,但没有一个能解决我的问题。
最佳答案
您的代码中的问题是您没有将正确的 url 传递给 window.open
。您需要包含 http://
window.open('http://localhost:3000/download');
关于javascript - 无法让浏览器启动从 express 下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54053901/