Combine ReactJS and Express in a single production process
In the development environment, you can run react and express in two individual node processes, react for front-end (i.e. running at localhost:3000), and express for the backend (i.e. running at localhost:2022). React can proxy to the express host from the package.json file
{
"proxy":"https://localhost:2022"
}
in this case, all requests like http://localhost:3000/api/record/get will be proxied to http://localhost:2022/api/record/get.
In the production environment, build react to production files (in build folder) and copy the production files to the static folder of express (in public folder), update the package.json file of express
{
"scripts": {
"start": "react-scripts start",
- "build": "react-scripts build",
+ "build": "react-scripts build && robocopy .\\build ..\\server\\public /mir",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
}
update the index.js file of express
const express = require('express');
const record = require('./routes/record');
const app = express();
const port = process.env.PORT || 2022;
const path = require('path');
const indexPath = path.join(__dirname, 'public', 'index.html');
app.use(express.json());
app.use(express.static('public')); // serve static files in public folder
app.use('/api/record', record);
app.get('*', (req, res, next) => {
res.sendFile(indexPath); // fallback all requests to index.html
});
app.listen(port, () => {
console.log(`running at http://localhost:${port}`);
});
创建时间:10/4/2022 11:37:27 PM
修改时间:10/5/2022 12:32:57 AM