【问题标题】:React Router - show PDF in new tab with window.openReact Router - 在带有 window.open 的新选项卡中显示 PDF
【发布时间】: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


【解决方案1】:

为什么不直接打开一个新窗口或设置href,所以不要只返回一个div,而是执行以下操作之一

  1. 您的应用程序所在的父窗口 - 有一条消息 &lt;div&gt; Return to homepage &lt;/div&gt; 并执行 window.open(url) 生成新请求,这里让您的节点服务器直接处理页面,而不使用将控制权传递给 React 的 App 中间件函数路由器。

  2. window.location.href- 记住,你超出了你的应用范围,我也相信通过目标,无论是_self 还是_blank 都会跳过路由器。

【讨论】:

  • 我不确定你的意思。我正在打开一个新窗口。但是 React Router 正在处理我认为的 URL,因此它不显示 PDF。 “父窗口”是什么意思?
  • App.js 是我添加此代码的位置:if (pdf_regex.test(window.location.pathname)) { return &lt;div /&gt;; // must return at least an empty div } else { // use React Router return ( &lt;Router&gt; 这就是您所说的“父窗口”的意思吗?
  • 是的,而不是 div - 返回一个 window.open
猜你喜欢
  • 1970-01-01
  • 2017-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-24
  • 1970-01-01
  • 2016-10-26
  • 2022-11-02
相关资源
最近更新 更多