【发布时间】:2020-11-26 20:41:28
【问题描述】:
我正在尝试在浏览器中的新选项卡中显示我的 PDF,但我感觉 React Router 正在接管并且无法正确显示。
这是我应该打开 PDF 的前端 React 函数:
const openPDF = (e) => {
const prettyPDFName = e.target.textContent;
openPDFAsync(prettyPDFName);
console.log('pdfTextContent: ', prettyPDFName);
const prettyFileName =
prettyPDFName
.substring(0, prettyPDFName.length - 4)
.replace(/[ ,.]/g, '') + '.pdf';
window.open(`/pdf/${prettyFileName}`, '_blank');
};
这会在地址栏中打开一个带有正确 URL 的新选项卡。但它只是显示了我的 React 应用,顶部是导航,中间是空白内容。
我在 SO 上发现了一些东西来阻止 React Router 接管特定的路由。所以在我的 app.js 中我尝试了这个:
const pdf_regex = /^\/pdf\/.*/;
// if using "/pdf/" in the pathname, don't use React Router
if (pdf_regex.test(window.location.pathname)) {
return <div />; // must return at least an empty div
} else {
// use React Router
return (
<Router>
...
这只是显示一个完全空白的页面,当我检查时,我猜只是一个空的 div。
有关更多信息,以下是从 openPDFAsync(prettyPDFName); 调用中调用的节点代码:
router.get('/openPDFFile', async (req, res) => {
const pretty_PDF_name = req.query.pdf;
const pdfFilename = (await SDS.getPDFFileName({ pretty_PDF_name }))
.dataValues.sheet_file_name;
const cleanPDFName =
pretty_PDF_name
.substring(0, pretty_PDF_name.length - 4)
.replace(/[ ,.]/g, '') + '.pdf';
const pdfFilepath = `./path/to/file/${pdfFilename}`;
console.log(cleanPDFName, pdfFilepath);
router.get(cleanPDFName, async (req, res) => {
res.sendFile(__dirname + pdfFilepath);
});
【问题讨论】:
-
不,这不是我正在做的。他们正在从客户端上的本地文件夹中导入 PDF。我正在从服务器提供 PDF 并尝试访问该 URL。
标签: javascript node.js reactjs pdf