give me code to display,add, update , delete courses and lectures records with express js and front end with react js with axios. with admin lgoin and logut and student login , logout, signup to check courses ChatGPT said:- To collaborate on this project, please log in to ChatGPT so we can use the ChatGPT canvas feature for writing and managing the code effectively. However, I can still give you a simplified version of the project structure and code snippets right here. This will include: Backend: Express.js with basic auth for admin and students Frontend: React.js with Axios for HTTP requests 🔧 Backend (Express.js) 1. Setup mkdir course-app-backend cd course-app-backend npm init -y npm install express mongoose bcryptjs jsonwebtoken cors 2. server.js const express = require('express'); const mongoose = require('mongoose'); const cors = require('cors'); const app = express(); app.use(cors()); app.use(express.json()); mongoose.connect('mongodb://localhost:27017/courseapp', { useNewUrlParser: true, useUnifiedTopology: true, }); require('./routes/authRoutes')(app); require('./routes/courseRoutes')(app); const PORT = 5000; app.listen(PORT, () => console.log(`Server running on port ${PORT}`)); 3. Models: models/User.js, models/Course.js // models/User.js const mongoose = require('mongoose'); const UserSchema = new mongoose.Schema({ username: String, password: String, role: { type: String, enum: ['admin', 'student'], default: 'student' }, }); module.exports = mongoose.model('User', UserSchema); // models/Course.js const mongoose = require('mongoose'); const CourseSchema = new mongoose.Schema({ title: String, description: String, lectures: [{ title: String, videoUrl: String }] }); module.exports = mongoose.model('Course', CourseSchema); 4. Authentication Routes: routes/authRoutes.js const jwt = require('jsonwebtoken'); const bcrypt = require('bcryptjs'); const User = require('../models/User'); module.exports = (app) => { app.post('/api/signup', async (req, res) => { const { username, password } = req.body; const hashed = await bcrypt.hash(password, 10); const user = new User({ username, password: hashed }); await user.save(); res.send({ message: 'User created' }); }); app.post('/api/login', async (req, res) => { const { username, password } = req.body; const user = await User.findOne({ username }); if (!user || !(await bcrypt.compare(password, user.password))) { return res.status(401).send({ error: 'Invalid credentials' }); } const token = jwt.sign({ id: user._id, role: user.role }, 'secretkey'); res.send({ token, role: user.role }); }); }; 5. Course Routes: routes/courseRoutes.js const Course = require('../models/Course'); const jwt = require('jsonwebtoken'); function authenticate(role) { return (req, res, next) => { const auth = req.headers.authorization; if (!auth) return res.status(401).send({ error: 'No token' }); const token = auth.split(' ')[1]; try { const decoded = jwt.verify(token, 'secretkey'); if (role && decoded.role !== role) return res.status(403).send({ error: 'Forbidden' }); req.user = decoded; next(); } catch { res.status(401).send({ error: 'Invalid token' }); } }; } module.exports = (app) => { // Admin only app.post('/api/courses', authenticate('admin'), async (req, res) => { const course = new Course(req.body); await course.save(); res.send(course); }); app.put('/api/courses/:id', authenticate('admin'), async (req, res) => { const updated = await Course.findByIdAndUpdate(req.params.id, req.body, { new: true }); res.send(updated); }); app.delete('/api/courses/:id', authenticate('admin'), async (req, res) => { await Course.findByIdAndDelete(req.params.id); res.send({ message: 'Deleted' }); }); // Public app.get('/api/courses', async (req, res) => { const courses = await Course.find(); res.send(courses); }); app.get('/api/courses/:id', async (req, res) => { const course = await Course.findById(req.params.id); res.send(course); }); }; 🎨 Frontend (React.js) 1. Setup npx create-react-app course-app-frontend cd course-app-frontend npm install axios react-router-dom 2. Folder Structure /src /pages LoginPage.js SignupPage.js AdminDashboard.js StudentDashboard.js /components CourseList.js CourseForm.js App.js 3. Axios Instance: api.js import axios from 'axios'; const instance = axios.create({ baseURL: 'http://localhost:5000/api', }); instance.interceptors.request.use(config => { const token = localStorage.getItem('token'); if (token) config.headers.Authorization = `Bearer ${token}`; return config; }); export default instance; 4. Example: LoginPage.js import React, { useState } from 'react'; import api from '../api'; import { useNavigate } from 'react-router-dom'; export default function LoginPage() { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const navigate = useNavigate(); const login = async () => { const res = await api.post('/login', { username, password }); localStorage.setItem('token', res.data.token); res.data.role === 'admin' ? navigate('/admin') : navigate('/student'); }; return (

Login

setUsername(e.target.value)} placeholder="Username" /> setPassword(e.target.value)} placeholder="Password" />
); } ======================================= Here's the code for both CourseList.js and CourseForm.js components, designed to work with the backend API and token-based authentication you've set up earlier. 📄 /components/CourseList.js This component fetches and displays all courses. It also supports delete/edit if the user is an admin. // /components/CourseList.js import React, { useEffect, useState } from 'react'; import api from '../api'; export default function CourseList({ isAdmin, onEdit }) { const [courses, setCourses] = useState([]); const fetchCourses = async () => { try { const res = await api.get('/courses'); setCourses(res.data); } catch (err) { console.error('Failed to fetch courses', err); } }; useEffect(() => { fetchCourses(); }, []); const handleDelete = async (id) => { if (!window.confirm('Are you sure you want to delete this course?')) return; try { await api.delete(`/courses/${id}`); fetchCourses(); } catch (err) { console.error('Delete failed', err); } }; return (

Courses

{courses.map(course => (

{course.title}

{course.description}

{isAdmin && ( <> )}
))}
); } 📄 /components/CourseForm.js This form is used by the admin to create or update courses, including multiple lectures. // /components/CourseForm.js import React, { useState, useEffect } from 'react'; import api from '../api'; export default function CourseForm({ selectedCourse, onSuccess }) { const [title, setTitle] = useState(''); const [description, setDescription] = useState(''); const [lectures, setLectures] = useState([]); useEffect(() => { if (selectedCourse) { setTitle(selectedCourse.title); setDescription(selectedCourse.description); setLectures(selectedCourse.lectures); } else { resetForm(); } }, [selectedCourse]); const resetForm = () => { setTitle(''); setDescription(''); setLectures([]); }; const addLecture = () => { setLectures([...lectures, { title: '', videoUrl: '' }]); }; const handleLectureChange = (index, field, value) => { const updated = [...lectures]; updated[index][field] = value; setLectures(updated); }; const handleSubmit = async (e) => { e.preventDefault(); const payload = { title, description, lectures }; try { if (selectedCourse) { await api.put(`/courses/${selectedCourse._id}`, payload); } else { await api.post('/courses', payload); } resetForm(); onSuccess(); // refresh list } catch (err) { console.error('Course save failed', err); } }; return (

{selectedCourse ? 'Edit Course' : 'Add New Course'}

setTitle(e.target.value)} required />