Render部署React Router+NodeJS应用:路径显示JSON而非HTML
问题:访问含
/events的URL时页面显示JSON而非React UI 我在Render上部署了前后端一体化的Web服务,应用已上线。但访问包含/events的URL(比如/events/55b79b2e-902f-44b1-b292-08ab669b76c6)时,页面不再渲染React UI,而是直接显示JSON数据:
// 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"
}
}
Render支持团队反馈这是应用自身问题,而非平台问题。我确认Render配置正确,以下是项目结构和关键代码,希望排查错误:
项目结构
/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
关键代码片段
backend\app.js
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}`); });
backend\data\events.js
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;
内容的提问来源于stack exchange,提问作者Sofiane Abou Abderrahim
相关产品推荐
相关产品推荐

