【问题标题】:How to serve ReactJS static files with expressJS?如何使用 expressJS 提供 ReactJS 静态文件?
【发布时间】:2017-11-24 20:25:59
【问题描述】:

问题

我已经成功提供了我的 React 应用程序的 index.html 文件,但是在 html 文件中替换了 <root>index.js 我的第一个 React 组件没有在 ReactDOM.render 上触发。 我如何让index.js 文件启动? 如果我对提供 React 应用程序的理解在某些方面存在偏差,我会大大 感谢您的澄清。

文件夹结构

  • / - 包含所有服务器端文件,包括server.js
  • /client/ - 包含所有 React 文件
  • /client/build/ - 包含所有生产就绪的客户端文件
    • /client/build/index.html
    • /client/build/static/js/main.[hash].js - 似乎是index.js 的缩小版本,其中包含ReactDOM.render for 我的 React 应用

当前部署

  • 我正在为 /client/ 目录使用 Facebook 的 create-react-app,包括 npm run build 以自动填充 /client/build/

文件片段

// server.js
let app = express();
app.use(express.static(path.join(__dirname, '../client/public')));

这成功加载了由提供的默认 index.html 创建反应应用程序

// index.html
<body>
  <noscript>
    You need to enable JavaScript to run this app.
  </noscript>
  <div id="root"></div>
</body>

上面的代码部分可能/可能没有用,但它是默认的 create-react-app 附带的 html 文件。我需要更换 带有引用缩小的 index.js 的脚本标记的 noscript 标记 文件?我已经尝试过了,没有任何改变,但也许是 因为不正确的相对路径制作。

【问题讨论】:

    标签: reactjs express static server create-react-app


    【解决方案1】:

    通过反复试验尝试了许多不同的事情后,解决方案非常简单:

    在静态调用中为 /client/build 文件夹提供服务,如下所示:

    app.use(express.static(path.join(__dirname, '../client/build')));
    

    【讨论】:

    • 请解释一下为什么会这样,因为如果您在文件夹结构中看到可能没有客户端/构建文件夹
    • 它在您使用npm run build 构建客户端站点后工作。您必须提供由 React 生成和交叉链接的客户端代码,而不是您处理的 public 文件夹。
    【解决方案2】:

    我有一段时间遇到同样的问题,我会说有效的解决方案分为两部分,以避免路由器出现问题

    1. 服务器来自 CRA 构建的静态(在您的情况下是客户端/构建)
    const buildPath = path.normalize(path.join(__dirname, '../client/build'));
    app.use(express.static(buildPath));
    
    1. 设置最终路由(在您服务器中的所有其他路由器之后)以使用以下内容:
    const rootRouter = express.Router();
    /* 
    * all your other routes go here
    */
    rootRouter.get('(/*)?', async (req, res, next) => {
      res.sendFile(path.join(buildPath, 'index.html'));
    });
    app.use(rootRouter);
    

    【讨论】:

      【解决方案3】:

      //在你的 react 应用运行时

      npm run build
      

      //在你的服务器上插入如下代码

      const path = require("path");
      app.use(express.static(path.join(__dirname,"nameOfYourReactApp","build")))
      
      //Replace nameOfYourReactApp with the name of your app
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-20
        • 2021-03-16
        • 1970-01-01
        • 2018-09-21
        • 2016-11-13
        相关资源
        最近更新 更多