我正在尝试让用户从我们的后端服务器下载文件。我已经尝试了来自这个问题的解决方案以及来自这里的后端,但很遗憾它们都没能成功。通过postman下载本身是有效的,但在react中无法实现。
附加信息:后端和前端在同一台机器上运行,但端口号分别为3001和3000。我不确定这是否有所帮助,但是在package.json中,react前端通过代理连接到后端。
客户端目前看起来像这样:
附加信息:后端和前端在同一台机器上运行,但端口号分别为3001和3000。我不确定这是否有所帮助,但是在package.json中,react前端通过代理连接到后端。
"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)触发保存对话框。