【发布时间】:2020-02-26 01:50:40
【问题描述】:
在使用带有 Express API 的 React 客户端时,React 客户端如何下载由 Express API 发送的文件?
问题:
- 如果我在浏览器栏中输入 url 并按 enter 文件下载成功。
- 但如果我使用 Axios 在我的 React 应用程序中调用相同的 url,文件不会下载。
快递服务器
// Route handler for /api/files/testfile
const getFile = async (req, res, next) => {
// File
const fileName = 'file.csv';
const filePath = path.join(__dirname, '/../../public/', fileName);
// File options
const options = {
headers: {
'x-timestamp': Date.now(),
'x-sent': true,
'content-disposition': "attachment; filename=" + fileName, // gets ignored
'content-type': "text/csv"
}
}
try {
res.download(
filePath,
fileName,
options
);
console.log("File sent successfully!");
}
catch (error) {
console.error("File could not be sent!");
next(error);
}
});
反应客户端
// When the user clicks the "Download as CSV" button
handleDownloadFile = () => {
axios
.get(
`/api/files/testfile`, {
responseType: 'blob',
headers: {
'Content-Type': 'text/csv',
}
}
)
.then(response => {
console.log(response.headers); // does not include content-disposition
console.log("File downloading successfully!");
})
.catch( (error) => {
console.error("File could not be downloaded:", error);
});
}
我读到这可能与 content-disposition 标头有关。我尝试设置(参见我上面的代码),但标头没有发送到客户端。
不受欢迎的“解决方案”:
在 React 应用程序中:创建一个新的
a元素,设置其href属性并通过 JavaScript 触发click。我正在寻找一个不需要这个 JS hack 的解决方案。在 React 应用程序中:使用
a和target="_blank"而不是 Axios。但是,这不适合我,因为它会绕过我的 axios 配置设置(API url、身份验证令牌等)
【问题讨论】:
标签: javascript reactjs express axios