[英]Cannot get browser to initiate download from express
繼這個問題之后,我無法讓瀏覽器從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');
出於安全目的,如果您想下載某些內容,則必須打開新標簽。
所以使用
window.open('http://localhost:3000/download','_blank')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.