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