![](/img/trans.png)
[英]Failed to download an image file from my node js server through my frontend (my backend and frontend are decoupled)
[英]Download JSON file from a node express server through my frontend
將文件上傳到項目目錄中的下載文件夾后,我已將其存儲。 我想從前端下載該保存的文件。 當我單擊下載按鈕時,它不會獲取文件。
當我在快遞應用程序上 go 到http://localhost:5000/download
時,我收到此錯誤消息
錯誤:發送后無法設置標頭。
快遞服務器代碼:
app.get('/download', (req, res) => {
res.send('file downloaded')
const file = './downloads/output.yml';
res.download(file, 'openapi.yml', (err) => {
if (err) {
console.log(err)
} else {
console.log('file downloaded')
}
});
});
前端應用代碼:
HTML:
<button class="download-btn">download</button>
腳本:
const handleDownload = async () => {
const res = await fetch("https://cors-anywhere.herokuapp.com/http://localhost:5000/download");
const blob = await res.blob();
download(blob, 'output.yml');
}
downloadBtn.addEventListener('click', handleDownload);
文件夾結構:
更新: Server.js
const uploadFiles = async (req, res) => {
const file = await req.files[0];
console.log(file)
postmanCollection = file.path;
outputFile = `downloads/${file.filename}.yml`
convertCollection();
res.json({ message: "Successfully uploaded files" });
}
app.post("/upload_files", upload.array("files"), uploadFiles);
任何人都請幫我解決這個問題。
您已經在使用res.send
,它將響應標頭發送回客戶端,從而結束請求響應周期,當您嘗試執行res.download
時,它會引發錯誤。 改為使用
app.get('/download', (req, res) => {
const file = './downloads/output.yml';
res.download(file, 'openapi.yml', (err) => {
if (err) {
console.log(err)
} else {
console.log('file downloaded')
}
});
});
res.send('file downloaded')
--->刪除這一行
您還需要更新您的 js 代碼
const handleDownload = async () => {
const res = await fetch("https://cors-anywhere.herokuapp.com/download"); //http://localhost:5000--->this is not required
const blob = await res.blob();
download(blob, 'output.yml');
}
downloadBtn.addEventListener('click', handleDownload);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.