小编典典

捆绑React / Express App进行生产

reactjs

我的应用程序使用“ 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文件中设置某些内容,我的应用程序是否捆绑用于生产?


阅读 285

收藏
2020-07-22

共1个答案

小编典典

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

app.use('/users', usersRouter);

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

其中的路径sendFile()需要指向index.htmlReact客户端/前端应用程序的位置。确切说来,这sendFile()完全取决于项目的结构。例如,如果您有一个名为React的文件夹client,其中有一个build
create-react-app 生成的文件夹npm run 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路线/路径,它会阻止你从拨打电话到,因为它会捕捉所有请求API阵营客户端应用程序,顺序是非常重要的。

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

希望有帮助!

2020-07-22