Apologies for any confusion. Here's a simplified example of code structure and implementation for the backend and frontend components of the Website Testimonial Management project using a MERN stack.
Backend (Node.js with Express.js):
- Create a file
server.js in the backend folder:
const express = require('express');
const cors = require('cors');
const dotenv = require('dotenv');
const connectDB = require('./config/db');
const testimonialRoutes = require('./routes/testimonial');
// Load environment variables
dotenv.config();
// Connect to MongoDB
connectDB();
// Create Express app
const app = express();
// Middleware
app.use(express.json());
app.use(cors());
// Routes
app.use('/api/testimonials', testimonialRoutes);
// Start the server
app.listen(process.env.PORT || 5000, () => {
console.log('Server is running on port ' + (process.env.PORT || 5000));
});
- Create a file
db.js in the backend/config folder to handle MongoDB connection:
const mongoose = require('mongoose');
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
console.log('Connected to the MongoDB database');
} catch (error) {
console.error('MongoDB connection failed -', error);
process.exit(1); // Exit process with failure
}
};
module.exports = connectDB;
- Create a file
testimonial.js in the backend/models folder to define the Testimonial data model:
const mongoose = require('mongoose');
const testimonialSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
content: {
type: String,
required: true,
},
image: {
type: String,
},
createdAt: {
type: Date,
default: Date.now,
},
});
const Testimonial = mongoose.model('Testimonial', testimonialSchema);
module.exports = Testimonial;
- Create a file
testimonial.js in the backend/controllers folder to handle testimonial-related routing logic:
const Testimonial = require('../models/testimonial');
// Controller for submitting a testimonial
exports.submitTestimonial = async (req, res) => {
try {
const { name, email, content, image } = req.body;
const newTestimonial = new Testimonial({
name,
email,
content,
image,
});
await newTestimonial.save();
res.status(201).json({ success: true, message: 'Testimonial submitted successfully' });
} catch (error) {
console.error('Failed to submit testimonial -', error);
res.status(500).json({ success: false, message: 'Server Error' });
}
};
// More controller methods for retrieving and managing testimonials can be added here
- Create a file
testimonial.js in the backend/routes folder to define API routes related to testimonials:
const express = require('express');
const router = express.Router();
const testimonialController = require('../controllers/testimonial');
// Route for submitting a testimonial
router.post('/', testimonialController.submitTestimonial);
module.exports = router;
Frontend (React.js):
- Create a file
TestimonialForm.js in the frontend/src/components folder to render a testimonial submission form:
import React, { useState } from 'react';
import testimonialService from '../services/testimonialService';
const TestimonialForm = () => {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [content, setContent] = useState('');
const [image, setImage] = useState(null);
const [errorMessage, setErrorMessage] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
try {
const testimonialData = {
name,
email,
content,
image,
};
await testimonialService.submitTestimonial(testimonialData);
// Reset form fields after successful submission
setName('');
setEmail('');
setContent('');
setImage(null);
setErrorMessage('');
} catch (error) {
setErrorMessage('Failed to submit testimonial. Please try again later.');
console.error('Failed to submit testimonial -', error);
}
};
return (
<form onSubmit={handleSubmit}>
{/* Form fields and input components */}
<button type="submit">Submit Testimonial</button>
{errorMessage && <p>{errorMessage}</p>}
</form>
);
};
export default TestimonialForm;
- Create a file
TestimonialList.js in the frontend/src/components folder to display the list of testimonials:
import React, { useEffect, useState } from 'react';
import testimonialService from '../services/testimonialService';
const TestimonialList = () => {
const [testimonials, setTestimonials] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchTestimonials = async () => {
try {
const testimonialsData = await testimonialService.getTestimonials();
setTestimonials(testimonialsData);
setLoading(false);
} catch (error) {
console.error('Failed to fetch testimonials -', error);
}
};
fetchTestimonials();
}, []);
if (loading) {
return <p>Loading testimonials...</p>;
}
return (
<div>
{/* Render testimonials */}
{testimonials.map((testimonial) => (
<div key={testimonial._id}>
{/* Testimonial content and details */}
</div>
))}
</div>
);
};
export default TestimonialList;
- Create a file
testimonialService.js in the frontend/src/services folder to handle API communication:
const testimonialService = {
submitTestimonial: async (testimonialData) => {
try {
const response = await fetch('/api/testimonials', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(testimonialData),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'Failed to submit testimonial');
}
return data;
} catch (error) {
throw new Error(error.message || 'Failed to submit testimonial');
}
},
getTestimonials: async () => {
try {
const response = await fetch('/api/testimonials');
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'Failed to fetch testimonials');
}
return data;
} catch (error) {
throw new Error(error.message || 'Failed to fetch testimonials');
}
},
};
export default testimonialService;
These code snippets were created to provide a general understanding of structuring the MERN project and its components. Please note that this is a simplified example and may require customization based on your project's specific needs, validation logic, data management, and UI design. Additionally, consider implementing necessary error handling, UI styling, form validation, and integrating any additional functionalities mentioned in the requirements.