【问题标题】:ReactJS download file from Express Server从 Express Server 下载 ReactJS 文件
【发布时间】:2019-05-26 13:07:25
【问题描述】:

我正在尝试让我的用户能够从我们的后端服务器下载文件。我已经尝试了来自 question 的解决方案以及来自 this 的后端。

遗憾的是,它们都没有奏效。下载本身通过邮递员工作,但不是反应。

附加信息:后端在同一台机器上运行,但在端口 3001 上,而前端在端口 3000 上运行 我不确定这是否有帮助,但反应前端通过 package.json 中的代理连接到后端

"proxy": "http://localhost:3001",

客户端目前是这样的:

    const download = require("downloadjs");

    const handleDownload = async () => {
      const res = await fetch("http://localhost:3001/download");
      const blob = await res.blob();
      download(blob, "test.pdf");
    }


    function App() {
      return (
        <div className="App">
          <header className="App-header">
            <button onClick={() => handleDownload().finally(() =>                 console.log("Passed through the whole handleDownload Request"))}>                </button>
          </header>
        </div>
      );
    }

而在后端,我使用的代码来自之前在 stackoverflow 上提出的问题。

    app.get('/getdoc', function (req, res) {
        res.download(path.join(__dirname, 'files/test.pdf'), function (err) {
            console.log(err);
        });
    });

这是通过 Postman 运行的代码,但它不会触发 React 中的下载。

react 中出现的错误是这样的:

    App.js:8 GET http://localhost:3001/download/test.pdf    net::ERR_CONNECTION_REFUSED

    Uncaught (in promise) TypeError: Failed to fetch

因此,前端的处理似乎是问题所在,因为它没有从浏览器 (Chrome) 触发保存对话框。

【问题讨论】:

    标签: node.js reactjs express download


    【解决方案1】:

    您对邮递员的请求将起作用,因为我假设您正在访问正确的端点,即“/getdoc”,这将允许您通过邮递员下载 pdf。

    但是,您的 fetch 请求似乎与提供 pdf 文档的 API 端点不匹配。这就是为什么你的 React 组件会在下载时给你错误。

    
    const handleDownload = async () => {
       const res = await fetch("http://localhost:3001/download");
       const blob = await res.blob();
       download(blob, "test.pdf");
      }
    
    //the fetch call for "http://localhost:3001/download"  will not hit '/getdoc'
    
    app.get('/getdoc', function (req, res) {
            res.download(path.join(__dirname, 'files/test.pdf'), function (err) {
                console.log(err);
            });
        });
    
    

    这是我实现 pdf 下载的方式。

    //resume route... this route is hit when you make a GET request to /api/resume
    const router = require('express').Router();
    module.exports = router;
    
    //when route is hit the resume is downloaded
    //aka /api/resume
    router.get('/', (req, res, next) => {
      try {
        const file = `${__dirname}/resume/resume.pdf`;
        res.download(file);
        console.log('here');
      } catch (err) {
        console.log(err);
      }
    });
    
    //react component
    import React from 'react';
    import download from 'downloadjs';
    
    const Resume = () => {
      return (
        <div>
          <button
            type="button"
            onClick={async () => {
              const res = await fetch('/api/resume');
              const blob = await res.blob();
              download(blob, 'test.pdf');
            }}
          >
            Download
          </button>
        </div>
      );
    };
    

    【讨论】:

    • 是否可以不使用“下载”模块下载文件?
    • 当然,您可以使用大量的软件包,或者您也可以不使用。下载文件最简单的方法是创建一个包含文件 URL 的链接,并将其包含在 HTML/React/Frontend 中
    【解决方案2】:

    试试这个:

    const handleDownload = () => {
    var reqObj = new XMLHttpRequest();
    reqObj.open('GET','http://localhost:3001/download',true);     // 'getpdf' is the URI to recongize your request at the server
    reqObj.send();
    
    reqObj.onreadystatechange = function() {
        var resObj = this;
        if(resObj.readyState == resObj.DONE) {
            if (resObj.status != 200) {
                console.log(200);
            } else if (resObj.status == 200){
                var resTxt = reqObj.responseText;
                window.location.assign(resTxt);    // Opens the pdf download prompt
            }
        }
    }
    

    【讨论】:

    • 我仍然得到 Err: App.js:7 GET localhost:3001/download net::ERR_CONNECTION_REFUSED 这是以下行: reqObj.open('GET',...);和状态码 = 0
    • 你能不能尝试直接在浏览器的url栏中访问localhost:3001/download
    • 它响应相同的错误,这很奇怪......在邮递员中我可以毫无问题地下载文件
    • 或者您可能必须指定获取的标头
    • 是的,但我仍然收到 ERR_CONNECTION_REFUSED 消息。我不知道要设置哪些标头,因为这是一个简单的获取请求
    猜你喜欢
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2018-11-14
    • 2020-01-27
    • 2021-08-08
    • 1970-01-01
    相关资源
    最近更新 更多