【发布时间】:2019-05-26 13:07:25
【问题描述】:
我正在尝试让我的用户能够从我们的后端服务器下载文件。我已经尝试了来自 question 的解决方案以及来自 this 的后端。
遗憾的是,它们都没有奏效。下载本身通过邮递员工作,但不是反应。
附加信息:后端在同一台机器上运行,但在端口 3001 上,而前端在端口 3000 上运行 我不确定这是否有帮助,但反应前端通过 package.json 中的代理连接到后端
"proxy": "http://localhost:3001",
客户端目前是这样的:
const download = require("downloadjs");
const handleDownload = async () => {
const res = await fetch("http://localhost:3001/download");
const blob = await res.blob();
download(blob, "test.pdf");
}
function App() {
return (
<div className="App">
<header className="App-header">
<button onClick={() => handleDownload().finally(() => console.log("Passed through the whole handleDownload Request"))}> </button>
</header>
</div>
);
}
而在后端,我使用的代码来自之前在 stackoverflow 上提出的问题。
app.get('/getdoc', function (req, res) {
res.download(path.join(__dirname, 'files/test.pdf'), function (err) {
console.log(err);
});
});
这是通过 Postman 运行的代码,但它不会触发 React 中的下载。
react 中出现的错误是这样的:
App.js:8 GET http://localhost:3001/download/test.pdf net::ERR_CONNECTION_REFUSED
Uncaught (in promise) TypeError: Failed to fetch
因此,前端的处理似乎是问题所在,因为它没有从浏览器 (Chrome) 触发保存对话框。
【问题讨论】:
标签: node.js reactjs express download