How to deploy a frontend React Router App with a NodeJS backend on Render

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>// 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"
}
}
</code>
<code>// 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" } } </code>
// 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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>/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
</code>
<code>/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 </code>
/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
  • backendapp.js:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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}`);
});
</code>
<code>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}`); }); </code>
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}`);
});
  • backenddataevent.js:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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;
</code>
<code>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; </code>
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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật