【发布时间】:2021-09-05 01:35:31
【问题描述】:
我希望能够将带有 nodejs 的 pdf 文件发送到前端。但是当我这样做时,我得到一个错误,我无法打开文件。这是错误(错误的翻译:加载 PDF 文档时发生错误):
我认为一切都很好,但仍然没有工作。
这里是nodeJS代码:
routerTrainer.get("/download-training", verifyJWT, async (req, res) => {
const { training_id } = req.headers;
let training = await Training.findOne({
where: { id: training_id },
});
if (training) {
res.download(`${path}${dirname}${training.file_id}`);
}
});
这里是 React 前端代码:
const downloadTraining = async (id) => {
const JWT = new ClassJWT();
const axiosReq = axios.create();
await JWT.checkJWT();
axiosReq
.get(`${serverPath}/download-training`, {
headers: {
training_id: id,
token: JWT.getToken(),
responseType: "blob"
},
})
.then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", "file.pdf");
document.body.appendChild(link);
link.click();
})
.catch((err) => console.log(err));
};
不要担心所有有 JWT 的东西,比如 verifyJWT 或 ClassJWT,这是 json Web 令牌的实现,它可以正常工作。
如果有人知道如何解决它,请告诉我。
【问题讨论】:
-
这能回答你的问题吗? React.js download pdf file from node backend
-
不,它不起作用