继从this https://stackoverflow.com/questions/53981780/angular-cannot-get-file-download-from-express-using-res-download?noredirect=1#comment94894474_53981780问题,我无法让浏览器启动 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';
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');
并通过 GET 请求导航到后端 URL(根据对我原来问题的响应),但它们都没有在浏览器中启动下载。
我认为这是一个前端问题,因为当我在控制台中双击下载时,它会打开。前端正在获取数据,但浏览器(chrome)没有下载数据。我也尝试了火狐,同样的结果。
有很多类似的问题,但没有一个能帮我解决这个问题。