Bundle React/Express App for production

此生再无相见时 提交于 2019-12-04 02:11:49

问题


My app is built with "create-react-app" and also Express.js as back-end. How should I set up for the app for production?

Here is my user.js file from Express:

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

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

module.exports = router;

I have "Proxy" setup in the package.json file in the React folder.

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

"create-react-app" has the command for build:

npm run build

Is my app bundled for production if I just run "npm run build" in the react folder or I have to setup something in my Express files?


回答1:


If Express acts as both your API and your application server, at a basic level you'd need to setup Express to load the index.html of the React application when no other API routes are caught. You would do this by using sendFile() along with Node's path, registering a "catch-all" route after all your other API endpoints, in the main file for your Express application.

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

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

The path within sendFile() needs to point to the location of the index.html of the React client/frontend applicaiton. Exactly what goes into sendFile() entirely depends on the structure of your project. If for exampple you have the React application in a folder called client which has a build folder generated by create-react-app npm run build, the sendFile() would look like:

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'));
});

The * in app.use() such as app.use('*', function (request, response)); means effectively all HTTP verbs (GET, POST, PUT, etc). If you do NOT put this after your API routes/paths, it will prevent your React client application from making calls to the API as it will catch all requests, order is very important.

Then you simply build the React application then run the Express application.

Hopefully that helps!



来源:https://stackoverflow.com/questions/50260684/bundle-react-express-app-for-production

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!