首页 > 解决方案 > 在 Node 中下载 PDF 文件并重定向到前端 React

问题描述

你能帮我在 Node.js 中下载一个文件并将页面重定向到前端吗?我正在使用 MERN 堆栈(Mongo、Express、React、Node)。

使用 Google Auth 进行身份验证后,我想在 Node 中下载一个文件,然后我想重定向页面。

router.get(
    '/auth/google/callback',
    passportGoogle.authenticate('google', {
        failureRedirect: '/',
    }),
    (req, res) => {
        try {
          var file = 'resume.pdf';
          res.download(file, (err => {
          if (err) {
                console.log(err)
          } else {
                window.location.href = '/';
          }
        }));
    }
);

我试过这段代码,但下载后它没有将页面重定向到前端。

标签: javascriptnode.jsreactjs

解决方案


   (req, res) => {
        try {
          var file = 'resume.pdf';
          res.download(file, (error => {
          if (!error) {
              window.location.replace("http://stackoverflow.com");
          } else {
                console.log(error)
          }
        }));
    } 
            catch {
                    console.log(error)
    }

推荐阅读