【问题标题】:Bundle React/Express App for production捆绑 React/Express 应用程序进行生产
【发布时间】:2018-05-10 03:56:26
【问题描述】:

我的应用是用“create-react-app”和 Express.js 作为后端构建的。 我应该如何设置应用程序以进行生产?

这是我来自 Express 的 user.js 文件:

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.json(['Hello World'])
});

module.exports = router;

我在 React 文件夹的 package.json 文件中设置了“代理”。

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

“create-react-app”有构建命令:

npm run build

如果我只是在 react 文件夹中运行“npm run build”或者我必须在我的 Express 文件中设置一些东西,我的应用程序是否捆绑用于生产?

【问题讨论】:

    标签: reactjs express production


    【解决方案1】:

    如果 Express 同时充当您的 API 和应用程序服务器,则在基本级别上,您需要设置 Express 以在没有捕获其他 API 路由时加载 React 应用程序的 index.html。您可以通过使用 sendFile() 和 Node 的 path 来做到这一点,在您的 Express 应用程序的主文件中所有其他 API 端点之后注册“catch-all”路由。

    app.use('/users', usersRouter);
    
    app.use('*', function (request, response) {
      response.sendFile(path.resolve(__dirname, 'index.html'));
    });
    

    sendFile() 内的路径需要指向 React 客户端/前端应用程序的index.html 的位置。 sendFile() 的确切内容完全取决于您项目的结构。例如,如果 React 应用程序位于名为 client 的文件夹中,其中有一个由 create-react-app npm run build 生成的 build 文件夹,sendFile() 看起来像:

    app.use(express.static(path.join(__dirname, 'client', 'build')));
    
    // API route
    app.use('/users', usersRouter);
    
    app.use('*', function (request, response) {
      response.sendFile(path.join(__dirname, 'client', 'build', 'index.html'));
    });
    

    app.use() 中的* 例如app.use('*', function (request, response)); 实际上表示所有HTTP 动词(GET、POST、PUT 等)。如果你没有把它放在你的 API 路由/路径之后,它将阻止你的 React 客户端应用程序调用 API,因为它会捕获所有请求,顺序非常重要。

    然后您只需构建 React 应用程序,然后运行 ​​Express 应用程序。

    希望对您有所帮助!

    【讨论】:

    • 很高兴为您提供帮助!希望总体上你需要做的事情是有意义的。 sendFile 中的确切路径将取决于您的项目结构,这实际上可以是您需要的任何东西。
    • app.use(express.static(path.resolve(__dirname, '../client/build')));app.get('*', function(request, response) { response.sendFile(path.resolve(__dirname, '../client/build', 'index.html')); });我在Express的主js文件中添加了这两个脚本,如何测试是否有效?
    • 当然可以。 Node 的path 有许多方法来构建路径以输入到sendFile()resolve() 绝对是一个选项,join() 也可以工作。该 sn-p 假定存在文件夹 client 与主 Express 应用程序文件处于同一级别。
    • 嗨,我尝试部署到 Heroku,但是当我打开应用程序时,我收到错误消息:ENOENT: no such file or directory, stat '/client/build/index.html',我的客户端文件夹与主要的 express js 文件处于同一级别,我在终端中检查,“index.html”确实存在于我的客户端/构建文件夹中。
    • 您在部署之前运行了npm run build 并确认index.html 是由create-react-app 生成的?这在部署之前是否在本地工作?如果不是,这可能是提供给sendFile() 的路径存在问题。请改用path.join(__dirname, 'client', 'build', 'index.html')
    猜你喜欢
    • 2021-01-11
    • 2016-10-04
    • 2018-11-23
    • 2017-11-14
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    相关资源
    最近更新 更多