0% found this document useful (0 votes)
6 views18 pages

Web Design and Development PR

The document outlines a comprehensive guide to building a full-stack application using the MERN stack (MongoDB, Express.js, React.js, Node.js). It covers essential topics such as CRUD operations, advanced queries, authentication, file uploads, real-time features, error handling, and deployment strategies. Additionally, it presents an industry-standard e-commerce project that integrates these technologies for practical application.

Uploaded by

vivesh2911
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
6 views18 pages

Web Design and Development PR

The document outlines a comprehensive guide to building a full-stack application using the MERN stack (MongoDB, Express.js, React.js, Node.js). It covers essential topics such as CRUD operations, advanced queries, authentication, file uploads, real-time features, error handling, and deployment strategies. Additionally, it presents an industry-standard e-commerce project that integrates these technologies for practical application.

Uploaded by

vivesh2911
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 18
8. 9. CONTENTS . Introduction to MongoDB, Express.js, React.js, and Node.js . CRUD Operations with MongoDB, Express.js, and Node.js . React.js Essentials . Advanced MongoDB Queries and Aggregation . Authentication and Authorization . File Uploads and Storage . Real-Time Features with WebSockets (Socket.IO) Error Handling and Logging Deployment and Scaling 10. Industry-Standard Project 1. Introduction to MongoDB, Express.js, React.js, and Node. Objective: Understand the MERN stack architecture and how each technology works together in a full-stack application. Theory: MongoDB: NoSQL database for storing data in flexible, JSON-like documents. * Express.js: Backend web framework for Node js to handle routes and middleware. * React.js: Frontend library to build user interfaces using components. © Node,js: JavaScript runtime used to execute backend code. Steps: 1. Install Node,js and MongoDB locally. 2. Use npx create-react-app to create the frontend. 3. Create a simple Express backend (server . js) with one test route. 4. Connect the frontend and backend using Axios. Example: // Backend: server.js const express = require('express'): const app = express(); const PORT = 5000; app.get('/', (req, res) => { res.send("Backend running successfully! ") ; ): app.listen(PORT, () => console.log(*Server started on port ${PORT}*)); // Frontend: App.js import React, { useEffect, useState } from ‘react’; import axios from ‘axios'; function App() { const [msg, setMsg] = useState(''); useEffect(() => { axios .get( ‘http: //localhost :5080/').then(res => setMsg(res.data)) ; }, (1): return

{msg}

; 2. CRUD Operations with MongoDB, Express.js, and Node.js Objective: Implement Create, Read, Update, and Delete operations using RESTful APIs. Theory: © CRUD refers to the basic operations for managing data: Create, Read, Update, Delete. © These are typically implemented using HTTP methods: POST, GET, PUT, DELETE Steps: 1. Create a MongoDB schema and model using Mongoose. 2. Set up Express routes for each operation. 3. Connect the frontend to interact with these APIs. Example Model (Mongoose): const mongoose = require('mongoose’ ) ; const UserSchema = new mongoose. Schema({ name: String, email: String, ); module.exports = mongoose.model(‘User', UserSchema) ; Example Routes (Express): const express = require('express'); const router = express.Router(); const User = require('./models/User'); // Create router .post('/users', async (req, res) => { const user = new User(req.body) ; await user.save(); res.send(user) ; y); // Read router.get('/users', async (req, res) => { const users = await User.find(); res.send(users) ; ); // Update router.put('/users/:id', async (req, res) => { const user = await User . findByIdAndUpdate(req.params.id, req.body) ; res.send(user) ; ); // Delete router.delete('/users/:id', async (req, res) => { await User .findByIdAndDelete(req.params.id); res.send({ message: ‘User deleted’ }); ); 3. React.js Essentials Objective: Build a dynamic front-end using components, hooks, and props. Theory: « React uses components to build reusable UI elements. © useState and useEf fect are hooks to manage state and side effects. © Props are used to pass data between components. Steps: 1. Create components using functional syntax. 2. Use useState to handle dynamic content. 3. Use useEf fect for data fetching. 4. Connect to backend APIs using Axios or Fetch. Example: function UserList() { const [users, setUsers] = useState([]); useEffect(() => { fetch('/api/users' ) .then(res => res.json()) .then(data => setUsers(data)); + (1): return (
    {users.map(user =>
  • {user .name}
  • ) }
yi 4. Advanced MongoDB Queries and Aggregation Objective: Use complex MongoDB queries and aggregation for reporting and analytics. Theory: © Aggregation is used to process data records and return computed results. © Common stages: $match, $group, $sort, $project, etc. Steps: 1. Use MongoDB Compass or Mongoose for writing aggregation pipelines. 2. Combine filtering and grouping for business logic. Example: // Total orders per user Order .aggregate([ { S$match: { status: ‘completed’ } }, { $group: { _id: ‘$userId', totalAmount: { $sum: "$amount' } } } 1); 5. Authentication and Authorization Objective: Secure applications using JWT for user sessions and role-based access. Theory: e Authentication verifies user identity. ¢ Authorization defines what authenticated users can access. « JWT (JSON Web Token) is used for stateless authentication. Steps: 1. Register/Login routes to generate JWT. 2. Store JWT on the client (localStorage or cookies). 3. Protect routes using middleware on the backend Example (Token Generation): const jwt = require(’jsonwebtoken' ) ; app.post('/login', (req, res) => { const token = jwt.sign({ userId: user._id }, "secretkey'); res.json({ token }); }); // Middleware function auth(req, res, next) { const token = req.headers.authorization?.split(" “)[1]; const verified = jwt.verify(token, ‘secretkey'); req.user = verified; next(); 6. File Uploads and Storage Objective: Upload files and store them using local or cloud storage. Theory: * Multer is used in Node.js to handle multipart/form-data. © Cloud services like Cloudinary or AWS S3 are used for file storage. Steps: 1. Install and configure multer. 2. Create an upload route. 3. (Optional) Integrate with Cloudinary or AWS S3. Example: const multer = require('multer'); const upload = multer({ dest: ‘uploads/' }); app.post('/upload’, upload.single(‘file'), (req, res) => res.send("File uploaded successfully") ; d): Re: ime Features with WebSockets (Socket Objective: Add real-time interactions such as chat or notifications. Theory: © WebSockets allow bidirectional communication between client and server. * Socket.IO simplifies real-time features in Node_js. Steps: 1. Install and configure Socket.IO on backend and frontend. 2. Use socket .emit and socket .on to send and receive events. Example: // Server io.on(‘connection', socket => { socket .on('message’, msg => { io.emit('message’, msg); 5 ); // Client socket.on('message', msg => { console. log("New message:", msg) ; Objective: Create a robust system to handle and log application errors. Theory: © Middleware can catch errors and return friendly messages. © Logging tools like winston record application activity. Steps: 1. Use Express error-handling middleware. 2. Log errors to files using Winston. Example: app.use((err, req, res, next) => { console.error(err.stack): res.status(508) .send("Something broke!"); yi; 9. Deployment and Scaling Objective: Host MERN apps on cloud platforms and ensure scalability. Theory: © Deployment platforms: Vercel/Netlify (Frontend), Render/Heroku (Backend) e CI/CD automates deployment from GitHub. Steps: 1. Push code to GitHub. 2. Deploy frontend (React) to Netlify. 3. Deploy backend (Express) to Render. 4. Set up environment variables and API endpoints. 5. (Optional) Use Docker and Nginx for advanced deployment. Industry-Standard Project E-Commerce Platform with Admin Panel Project Overview This project simulates a real-world e-commerce application like Amazon or Flipkart. Users can browse a variety of products, add them to a shopping cart, and place orders securely. An admin panel allows the platform owner to manage products, view all orders, and handle users. This enhances both frontend and backend development skills with proper database integration and secure authentication. Tech Stack Layer Technology Used Frontend React js, Redux Toolkit, Tailwind CSS Backend Node_js, Express.js Database MongoDB + Mongoose ORM Authentication JWT (JSON Web Token) + Berypt.is Image Upload Cloudinary or Multer (for local dev) Deployment Vercel (frontend) & Render (backend) Folder Structure ecommerce-app/ [+ client’ # React Frontend | L- components/ | E+ pages/ | F-redux/ | Apps [+ server! # Node.js + Express Backend |— controllers/ |— routes/ | | /-_ moaels/ | | L—-serverjs Sample Code Snippets Create Product API (Express.js) router.post('/add', verifyAdmin, async (req, res) => { const newProduct = new Product(req.body) ; await newProduct.save(); res.status(201).json({ message: "Product created", product: newProduct }); d); Add to Cart (Redux + React) dispatch(addToCart({ id: product._id, name: product .name, price: product.price, quantity: 1, )); JWT Authentication (Login Route) const token = jwt.sign({ id: user._id, role: user.role }, process.env.JWT_SECRET, { expiresIn: '3d' }); res.status(2@8).json({ user, token }); ii Project Visuals Fan & RCShop Stay Cool & Comfortable ine Pte “Rem Som fonts faerie Featured Products = -_ -- ‘ser i * Ba — a mn me Sine vom a wns Cart Visuals ‘FShopping Cart User Orders Visuals My Orders Order weu2ed2b7c08AcADacAae4e4s ‘Shippin Adress tas oso, oat 32055 a Order tems Slit hr Conditioner sos omer Summary van Seo vot sma ackto Ordre ‘50.00 s000 2000 $070.99 © Admin Panel FandAC ain in ashore Gann @ dssnboors Dashboard own we mw" 2 wee me uaa rises [saison ian ne Stas re me ome a ° 1 1 2 Recent Ors owes = _ v soe sees 00 Vier STAREX UNIVERSITY GURUGRAM SCHOOL OF COMPUTER SCIENCE B.Tech Computer Science & Engineering NAME :CHETAN SINGH ROLL NO: 2340801039 SUBJECT: WEB DESIGN AND DEVELOPMENT COURSE: B.TECH (CSE )

You might also like