ReactJS 从 Express Server 下载文件

Pat*_*k.H 3 download node.js express reactjs

我试图让我的用户能够从我们的后端服务器下载文件。我已经尝试过此问题的解决方案以及此问题的后端。

遗憾的是他们都没有工作。下载本身可以通过邮递员进行,但不能在反应中进行。

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

"proxy": "http://localhost:3001",
Run Code Online (Sandbox Code Playgroud)

客户端目前看起来是这样的:

    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>
      );
    }
Run Code Online (Sandbox Code Playgroud)

在后端,我使用的代码与之前在 stackoverflow 上提出的问题相同。

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

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

反应中发生的错误如下所示:

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

    Uncaught (in promise) TypeError: Failed to fetch
Run Code Online (Sandbox Code Playgroud)

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

Que*_*der 8

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

但是,您的提取请求似乎与提供 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);
        });
    });

Run Code Online (Sandbox Code Playgroud)

这是我实现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);
  }
});
Run Code Online (Sandbox Code Playgroud)
//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>
  );
};
Run Code Online (Sandbox Code Playgroud)

  • 当然,您可以使用大量的软件包,也可以不使用软件包。下载文件的最简单方法是创建一个包含文件 URL 的链接,并将其包含在 HTML/React/Frontend 中 (2认同)