I am working on an Express/React app using web pack to bundle. I have two routes in my index.js file. The route to App.js is "/". I have a route to Chat.js at "chat". The route to App works and shows the test heading from / in the browser. The route to Chat gives the error {"message":"Page not found for GET /chat"} in the browser. Here is index.js:
"react": "^18.2.0", "react-dom": "^18.2.0", "react-router-dom": "^6.4.3",
I have tried changing the route from <Route path='/chat' to <Route path='chat'
I've been using react for 2 years and since the new version of react (18) and react-router-dom (6.4) I haven't been able to get a single app to work
I expected the Chat page to display in the browser and instead got {"message":"Page not found for GET /chat"}
CodePudding user response:
Use this code for your server.js file:
const express = require('express');
const path = require('path');
const app = express();
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config();
}
app.use('/dist', express.static(path.join(__dirname, 'dist')));
// If no other routes are hit, send the React app
app.use((req, res) => res.sendFile(path.join(__dirname, '/index.html')));
app.use((req, res, next) => {
next({
status: 404,
message: `Page not found for ${req.method} ${req.url}`,
});
});
app.use((err, req, res, next) => {
res.status(err.status || 500).send({
message: err.message || JSON.stringify(err),
});
});
app.listen(process.env.PORT, () => console.log('Listening on PORT ', process.env.PORT));
I've run this locally using your repo and it works. I've also pushed the working changes to an example repo in GitHub (https://github.com/rsg71/react-stack-overflow).
What you needed to change was send the React app without specifying the GET / endpoint:
Previously you had:
app.get('/', (req, res, next) => {
try {
res.sendFile(path.join(__dirname, 'index.html'));
} catch (error) {
next(error);
}
});
What you need instead is:
// If no other routes are hit, send the React app
app.use((req, res) => res.sendFile(path.join(__dirname, '/index.html')));
Now the react-router-dom package can handle routing. Otherwise, you are relying on express for the routing of your React app which is not what you want.