I am new to react, and I am trying to build a chat-app with it. I used react-router to load different components according to the url. In my react project foler (client/src/index.js), the code is as follows:
import {BrowserRouter as Router, Route} from 'react-router-dom';
...
ReactDOM.render(
<Router>
<div>
<Route exact path='/' component={App} />
<Route path='/customer' component={CustomerPage} />
<Route path='/support/:support_id' component={SupportPage} />
</div>
</Router>,
document.getElementById('root')
);
...
It works find when I start it in the react folder with "npm start". But when I run "npm run build" and serve the static files with express server, it can only serve the App page in the '/' path, while for '/customer' and '/support/:support_id" path, it loads nothing.
In the express server folder, I load the static files in the following way:
server/app.js:
...
var indexRouter = require('./routes/index');
app.use('/static', express.static(path.join(__dirname, '../client/build//static')));
app.use('/', indexRouter);
...
server/routes/index.js:
...
router.get('/', function(req, res) {
res.sendFile('index.html', {root: path.join(__dirname, '../../client/build/')});
});
...
Any help will be appreciated!
React Router does all the routing in the browser, so you need to make sure that you send the index.html
file to your users for every route.
This should be all you need:
app.use('/static', express.static(path.join(__dirname, '../client/build//static')));
app.get('*', function(req, res) {
res.sendFile('index.html', {root: path.join(__dirname, '../../client/build/')});
});
You must serve the static files and handle any request in your index.js:
const express = require('express');
const path = require('path');
const app = express();
// Serve the static files from the React app
app.use(express.static(path.join(__dirname, 'client/build')));
// Handles any requests that don't match the ones above
app.get('*', (req,res) =>{
res.sendFile(path.join(__dirname+'/client/build/index.html'));
});
const port = process.env.PORT || 5000;
app.listen(port);
console.log('App is listening on port ' + port);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With