Express JS Serve React JS Site With Path Longer Than Just Subdirectory

46 views Asked by At

I have a React JS website being served by an Express JS Backend. My app has an api to fetch data from a database, and then at the end sends the built website. Here is my index.js in my backend:

const express = require('express');
const path = require('path');
const cors = require('cors');

require('dotenv').config();

const app = express();
const frontEndPath = path.join(__dirname, '..', 'frontend', 'build')

app.use(cors());
app.use(express.json());
app.use(express.static(frontEndPath));

app.get('/api', (req, res) => {
    res.send('Hello from the API!')
})

// Various API Routes From Different Files I Have Omitted

app.get('/*', (req, res) => {
    res.sendFile(path.join(frontEndPath, 'index.html'));
});

const PORT = process.env.PORT;
app.listen(PORT, () => {
    console.log('Running on port', PORT);
});

I am using React-Router-Dom for the pages - here is the Routes:

<div className='main'>
    <Routes>
        <Route path='/' element={<Dashboard />} />
        <Route path='/repairs' element={<Repairs />} />
        <Route path='/repairs/repair/:id' element={<Repair />} />
        <Route path='/calendar' element={<Calendar />} />
        <Route path='/customers' element={<Customers />} />
        <Route path='/settings' element={<Settings />} />
    </Routes>
</div>

One of the pages of the React site has a parameter in its URL, and it works just fine except when I reload that page or try to get to it directly from the URL. At that stage it doesn't show the usual "Could not get /", and also doesn't show the page I have for an invalid parameter - it just shows completely blank.

I have tried tweaking the /* route and adding a separate route for that page, but haven't had any success. I've probably missed something, but I can't find the answer anywhere.

0

There are 0 answers