我正试图在浏览器中的一个新选项卡中显示我的PDF,但我感觉React Router正在接管它,无法正确显示它。
这是我的前端React函数,它应该打开PDF:
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接管特定路由的东西。所以在我的应用程序.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);
});
为什么不打开一个新窗口或设置href,而不是只返回一个div,请执行以下之一
-
您的应用程序所在的父窗口-有一条消息
<div> Return to homepage </div>
并执行一个生成新请求的window.open(url)
,在这里让您的节点服务器直接处理页面,而不使用将控制权传递给React路由器的App
中间件功能。 -
window.location.href
-记住,你超出了你的应用范围,我也相信通过目标,无论是_self
还是_blank
都会跳过路由器。