【发布时间】:2019-08-05 21:39:14
【问题描述】:
我的服务器上有一个文件(Node.js + Express)。我需要将文件从服务器下载到用户的计算机。 在 React 应用程序中,我调用了下载文件的函数:
downloadFileFromServer(file) { // file -- name of file
fetch(`${Config.baseUrl}/download-file/${this.props.params.idEvent}/${file}`, {
method: 'GET'
})
.then((response) => {
if (response.status >= 400) {
throw new Error('Bad response from server');
}
return response;
});
}
在后端我有这条路线:
app.route('/download-file/:idEvent/:fileName')
.get((req, res) => {
const id = `id${req.params.idEvent}`;
const dir = `${Config.basePath}/${id}/${req.params.fileName}`;
res.download(dir); // dir -- path to server's files. (something like this: 'var/www/... path to directory ...')
});
结果我没有任何结果。什么也没发生,控制台(前端、后端)是空的,没有错误。
为什么我不能下载文件?如何解决?
【问题讨论】:
-
fetch不直接返回数据。您可能需要先致电response.blob或response.text:developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch -
为什么要将 id 与 req.params.idEvent 连接起来?您的参数 id 是否总是以“id”开头,即 id43768926?
-
在你的下载逻辑中试试这个 location.path =
${Config.baseUrl}/download-file/${this.props.params.idEvent}/${file}
标签: javascript node.js reactjs file express