I deployed my project on render.com and my app is live at this link https://react-router-events-j6yu.onrender.com/
However, when I go to an URL with /events
, the UI disappears and the page displays as follows:
// 20240523233320
// https://react-router-events-j6yu.onrender.com/events/55b79b2e-902f-44b1-b292-08ab669b76c6
{
"event": {
"title": "Test again...",
"image": "https://www.meydanfz.ae/wp-content/uploads/2021/10/Events-1024x576.png",
"date": "2024-06-08",
"description": "Test",
"id": "55b79b2e-902f-44b1-b292-08ab669b76c6"
}
}
It renders JSON data instead of HTML.
I contacted the Render's support and they said that it might be that this is an application issue and not a render-specific issue.
Indeed, I created a "Web service" on render to host both my backend & my frontend apps at the same time.
I think the configuration is correct on Render.
So, I show you some of my code here so that you might detect the error hopefully.
La structure de mon projet est la suivante:
/my-project
/backend
app.js
events.json
/data
events.js
/routes
events.js
/util
error.js
validation.js
/frontend
/build
index.html
// other build files
src
// my React source files
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const eventRoutes = require('./routes/events');
const app = express();
const PORT = process.env.PORT || 8080;
app.use(bodyParser.json());
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PATCH,DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
next();
});
// Serve static files from the React app
app.use(express.static(path.join(__dirname, '../frontend/build')));
// API routes
app.use('/events', eventRoutes);
// The "catchall" handler: for any request that doesn't match one above, send back React's index.html file.
app.get('*', (req, res) => {
console.log('Serving index.html for request:', req.url);
res.sendFile(path.join(__dirname, '../frontend/build', 'index.html'));
});
// Error handling middleware
app.use((error, req, res, next) => {
const status = error.status || 500;
const message = error.message || 'Something went wrong.';
res.status(status).json({ message: message });
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
const fs = require('node:fs/promises');
const path = require('path');
const { v4: generateId } = require('uuid');
const { NotFoundError } = require('../util/errors');
// Utilisation de path.resolve pour garantir le bon chemin d'accès
const dataFilePath = path.resolve(__dirname, '../events.json');
async function readData() {
try {
console.log('Reading data from:', dataFilePath); // Ajout de log pour vérifier le chemin
const data = await fs.readFile(dataFilePath, 'utf8');
return JSON.parse(data);
} catch (error) {
console.error('Failed to read data:', error);
throw new Error('Could not read events data.');
}
}
async function writeData(data) {
try {
console.log('Writing data to:', dataFilePath); // Ajout de log pour vérifier le chemin
await fs.writeFile(dataFilePath, JSON.stringify(data));
} catch (error) {
console.error('Failed to write data:', error);
throw new Error('Could not write events data.');
}
}
async function getAll() {
const storedData = await readData();
if (!storedData.events) {
throw new NotFoundError('Could not find any events.');
}
return storedData.events;
}
async function get(id) {
const storedData = await readData();
if (!storedData.events || storedData.events.length === 0) {
throw new NotFoundError('Could not find any events.');
}
const event = storedData.events.find(ev => ev.id === id);
if (!event) {
throw new NotFoundError('Could not find event for id ' + id);
}
return event;
}
async function add(data) {
const storedData = await readData();
storedData.events.unshift({ ...data, id: generateId() });
await writeData(storedData);
}
async function replace(id, data) {
const storedData = await readData();
if (!storedData.events || storedData.events.length === 0) {
throw new NotFoundError('Could not find any events.');
}
const index = storedData.events.findIndex(ev => ev.id === id);
if (index < 0) {
throw new NotFoundError('Could not find event for id ' + id);
}
storedData.events[index] = { ...data, id };
await writeData(storedData);
}
async function remove(id) {
const storedData = await readData();
const updatedData = storedData.events.filter(ev => ev.id !== id);
await writeData({ events: updatedData });
}
exports.getAll = getAll;
exports.get = get;
exports.add = add;
exports.replace = replace;
exports.remove = remove;
I can give you more detail if needed.
This is most definitely an application issue and not an uncorrect configuration on Render.
Indeed, what's happening here is a mix up around client side routing and server paths.
When you're browsing the site and clicking on the "Events" navigation link, that's not really loading /events
from the server - it's the React Router changing address to make it look like it's that path and then your JS is fetching /events
from the server.
When you refresh, you are telling the browser to load from /events
- which is the path you have your JSON loading from.
To resolve, you should update the server path /events
(https://github.com/sofiane-abou-abderrahim/react-router-events/blob/test/backend/app.js#L21) to be something like /data
and then update your JS to fetch from /data
. (https://github.com/sofiane-abou-abderrahim/react-router-events/blob/test/frontend/src/pages/Events.js#L21)
That way, clicking on "Events", will change the browser to /events
and load the data from /data
, a refresh means your "* catch all path in server" would redirect and React Router handle it.