How to serve React JS static files with express JS?
Install express and create a new directory for the project.
Create a new file called server.js in the project directory.
Use the following code in server.js to set up a basic express server:
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'build')));
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`App is running on port ${port}`);
});
- Install React and build the project using the following commands:
npx create-react-app my-app
cd my-app
npm run build
- Run the express server using the following command:
node server.js
- Access the React app by navigating to http://localhost:3000 in a web browser.