0% found this document useful (0 votes)
22 views440 pages

NodeJs + ExpressJs + MongoDB-notes

The document provides comprehensive course notes on Node.js, Express.js, and MongoDB, covering topics such as Node.js features, server architecture, and the installation process. It includes lessons on JavaScript usage on both client and server sides, as well as practical guidance on creating a Node server and understanding the request-response cycle. The notes are structured to facilitate learning about full-stack JavaScript development and the underlying technologies involved.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views440 pages

NodeJs + ExpressJs + MongoDB-notes

The document provides comprehensive course notes on Node.js, Express.js, and MongoDB, covering topics such as Node.js features, server architecture, and the installation process. It includes lessons on JavaScript usage on both client and server sides, as well as practical guidance on creating a Node server and understanding the request-response cycle. The notes are structured to facilitate learning about full-stack JavaScript development and the underlying technologies involved.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

NodeJs + ExpressJs + MongoDB

Course Notes
Contains 1 PDF lessons

Generated: 16 February 2026

KnowledgeGate
Module

Nodejs

Topic
NodeJS

Subtopic
NodeJS

Lesson Lesson 1 of 1
NodeJs_Notes
Playlist Link
NodeJS
Complete Course
Introduction to NodeJS
1. Pre-requisites
2. What is NodeJS
3. NodeJs Features
4. JavaScript on Client
5. JavaScript on Server
6. Client Code vs Server Code
7. Other uses of NodeJs
8. Server architecture with NodeJs
JS is required for NodeJS
React is recommended before NodeJS
[Link] is NodeJS

1. JavaScript Runtime: [Link] is an open-source,


cross-platform runtime environment for executing
JavaScript code outside of a browser.
2. NodeJs is a JavaScript in a different environment means
Running JS on the server or any computer.
3. Built on Chrome's V8 Engine: It runs on the V8 engine,
which compiles JavaScript directly to native machine
code, enhancing performance.
4. V8 is written in C++ for speed.
5. V8 + Backend Features = NodeJs
[Link] is NodeJS
1. Design: Features an event-driven,
non-blocking I/O model for efficiency.
2. Full-Stack JavaScript: Allows using
JavaScript on both server and client
sides.
3. Scalability: Ideal for scalable network
applications due to its architecture.
4. Versatility: Suitable for web, real-time
chat, and REST API servers.
3. NodeJs Features
(Added)

1. Non-blocking I/O: Designed to perform non-blocking operations


by default, making it suitable for I/O-heavy operations.
2. Networking Support: Supports TCP/UDP sockets, which are
crucial for building lower-level network applications that
browsers can’t handle.
3. NodeJs Features
(Added)

1. File System Access: Provides APIs to read and write files directly,
which is not possible in browser environments for security
reasons.
2. Server-Side Capabilities: [Link] enables JavaScript to run on the
server, handling HTTP requests, file operations, and other
server-side functionalities.
3. Modules: Organize code into reusable modules using require().
3. NodeJs Features
(Removed)

1. Window Object: The global window object, which is part of web


browsers, is absent in [Link].
2. DOM Manipulation: [Link] does not have a built-in Document Object
Model (DOM), as it is not intended to interact with a webpage's
content.
3. BOM (Browser Object Model): No direct interaction with things like
navigator or screen which are part of BOM in browsers.
3. NodeJs Features
(Removed)

Web-Specific APIs: APIs like localStorage, sessionStorage,


and browser-based fetch are not available in [Link].
4. JavaScript on Client

1. Displays Web Page: Turns HTML code into what you


see on screen.
2. User Clicks: Helps you interact with the web page.
3. Updates Content: Allows changes to the page using
JavaScript.
4. Loads Files: Gets HTML, images, etc., from the
server.
5. JavaScript on Server
1. Database Management: Stores, retrieves, and manages
data efficiently through operations like CRUD (Create,
Read, Update, Delete).
2. Authentication: Verifies user identities to control access to
the system, ensuring that users are who they claim to be.
3. Authorization: Determines what authenticated users are
allowed to do by managing permissions and access
controls.
4. Input Validation: Checks incoming data for correctness,
completeness, and security to prevent malicious data entry
and errors.
5. Session Management: Tracks user activity across various
requests to maintain state and manage user-specific
settings.
5. JavaScript on Server
6. API Management: Provides and handles interfaces for
applications to interact, ensuring smooth data exchange and
integration.
7. Error Handling: Manages and responds to errors effectively to
maintain system stability and provide useful error messages.
8. Security Measures: Implements protocols to protect data from
unauthorized access and attacks, such as SQL injection and
cross-site scripting (XSS).
9. Data Encryption: Secures sensitive information by encrypting
data stored in databases and during transmission.
10. Logging and Monitoring: Keeps records of system activity to
diagnose issues and monitor system health and security.
6. Client Code vs Server Code
1. User/client can’t access server code directly.
2. Client must raise requests for particular APIs to
3. access certain features or data.
Environment Access: Server-side JavaScript
accesses server features like file systems and
databases.
4. Security: Server-side code can handle sensitive
operations securely, while client-side code is
exposed and must manage security risks.
5. Performance: Heavy computations are better
performed on the server to avoid slowing down
the client.
6. Client Code vs Server Code
6. Resource Utilization: Servers generally offer more
powerful processing capabilities than client
devices.
7. Data Handling: Server-side can directly manage
large data sets and database interactions, unlike
client-side JavaScript.
8. Asynchronous Operations: Server-side JavaScript is
optimized for non-blocking I/O to efficiently
manage multiple requests.
9. Session Management: Servers handle sessions and
user states more comprehensively.
10. Scalability: Server-side code is designed to scale
and handle requests from multiple clients
7. Other uses of NodeJs
1. Local Utility Scripts: Automates tasks and
processes files locally, like using shell scripts
but with JavaScript.
2. Internet of Things (IoT): Develops server-side
applications for IoT devices, managing
communications and data processing.
3. Scripting for Automation: Automates
repetitive tasks in software development
processes, such as testing and deployment.
7. Other uses of NodeJs

Real-Time Applications: Efficiently manages real-time data


applications, such as chat apps and live updates, using
WebSockets.
7. Other uses of NodeJs

Desktop Applications: Creates cross-platform desktop


applications using frameworks like Electron.
7. Other uses of NodeJs
Build Tools: Powers build processes
for front-end technologies using
tools like:
• Webpack
• Grunt
• Gulp
• Browserify
• Brunch
• Yeoman
8. Server architecture with NodeJs

Nodejs server will:


[Link] server and listen to incoming requests
[Link] logic: validation, connect to db, actual processing of data
[Link] response HTML, JSON, CSS, JS
Revision

1. P•Crlicek
•Second level -tor eediqt Muaistseri tteexts styles
•is NodeJS
•Third level
2. Wha•tFo urth level
Fifth level

3. NodeJs Features
4. JavaScript on Client
5. JavaScript on Server
6. Client Code vs Server Code
7. Other uses of NodeJs
8. Server architecture with NodeJs
2. Installation of NodeJS
1. What is IDE
2. Need of IDE
3. MAC Setup
• Install latest Node & VsCode
4.
Windows Setup
5. •Install latest Node & VsCode
Linux Setup
6. •Install latest Node & VsCode
7. VsCode (Extensions and Settings)
8. Executing first .js file
9. What is REPL
Executing Code via REPL
2.1 What is IDE
1. IDE stands for Integrated
Development Environment.
2. Software suite that
consolidates basic tools
required for software
development.
3. Central hub for coding,
finding problems, and testing.
4. Designed to improve
developer efficiency.
2.2 Need of IDE
1. Streamlines development.
2. Increases productivity.
3. Simplifies complex tasks.
4. Offers a unified
workspace.
5. IDE Features
1. Code Autocomplete
2. Syntax Highlighting
3.
4.
Version Control
Error Checking
2.3 MAC Setup
•Click to edit Master text styles
• Second level
• Third level
• Fourth level
•Fifth level
2.3 MAC Setup
(Install latest Node)
Search Download NodeJS
2.3 MAC Setup
(Install VsCode)
Se•aCrlicckh
•Second level
t oV eSd osgle
itC Moadsteer otenxt Gstyole
•Third level
• Fourth level
•Fifth level
2.4 Windows Setup
•Click to edit Master text styles
• Second level
• Third level
• Fourth level
•Fifth level
2.4 Windows Setup
(Install latest Node)
Search Download NodeJS
2.4 Windows Setup
(Install VsCode)
Se•aCrlickh t oV eSd itC Moadster otenxt Gstyoleosgle
•Second level
•Third level
• Fourth level
•Fifth level
2.5 Linux Setup
2.5 Linux Setup
(Install latest Node)
Search Download NodeJS
2.5 Linux Setup
(Install VsCode)
Se•aCrlickh t oV eSd itC Moadster otenxt Gstyoleosgle
•Second level
•Third level
• Fourth level
•Fifth level
2.6 VsCode
(Extensions and Settings)

1. Prettier (Format on Save)


2. Line Wrap
3. Tab Size from 4 to 2
2.7 Executing first .js file
[Link] Node Command: Use node [Link] to
execute a JavaScript file in the [Link] environment.
[Link] Syntax: Use require('module') to include built-in
or external modules, or other JavaScript files in your
code.
[Link] Code: require helps organize code into reusable
modules, separating concerns and improving
maintainability.
[Link]: Modules loaded with require are cached,
meaning the file is executed only once even if included
multiple times.
2.8 What is REPL
1. Streamlines Interactive Shell: Executes
JavaScript code interactively.
2. Quick Testing: Ideal for testing and
debugging code snippets on the fly.
3. Built-in Help: Offers help commands via
.help.
4.
Session Management: Supports saving
5. (.save) and loading (.load) code sessions.
[Link] API Access: Provides direct access
6. to [Link] APIs for experimentation.
Customizable: Allows customization of
prompt and behaviour settings.
2.9 Executing Code via REPL
Revision

1. What isedit
•Click to IDE Master text styles
2. NeeSdec

oonfd leIvDel
•ThirdlevelE
3. •uFpifthlevel
MAC S•eFtourth level
• Install latest Node & VsCode
4.
Windows Setup
5. •Install latest Node & VsCode
Linux Setup
6. •Install latest Node & VsCode
7. VsCode (Extensions and Settings)
8. Executing first .js file
9. What is REPL
Executing Code via REPL
3. First Node Server
[Link] DNS Works?
[Link] Web Works?
[Link] are Protocols?
[Link] Core Modules
5. Require Keyword
[Link] first Node Server
3.1 How DNS Works?
[Link] Name Entry: User types a domain (e.g.,
[Link]) into the browser.
[Link] Query: The browser sends a DNS query to resolve
the domain into an IP address.
3. DNS Server: Provides the correct IP address for the
domain.
[Link] Connects: The browser uses the IP to connect
to the web server and loads the website.
3.1 How DNS Actually Works?
1. Root DNS: Acts as the starting point for DNS resolution. It
directs queries to the correct TLD server (e.g., .com, .org).
[Link] (Top-Level Domain) DNS: Handles queries for specific
top-level domains (e.g., .com, .net) and directs them to the
authoritative DNS server (e.g., Verisign for .com, PIR for .org)
3. Authoritative DNS: Contains the actual IP address of the
domain and answers DNS queries with this information.(e.g.,
Cloudflare, Google DNS).
3.2 How Web Works?
[Link] Request Initiation: The client (browser) initiates a
network call by entering a URL.
[Link] Resolution: The browser contacts a DNS server to
get the IP address of the domain.
[Link] Connection: The browser establishes a TCP
connection with the server's IP address.
[Link] Request: The browser sends an HTTP request to
the server.
5. Server Processing: The server processes the request and
6. prepares a response.
HTTP Response: The server sends an HTTP response back
to the client.
[Link] Transmission: The response travels back to the
client over the network.
[Link] Receives Response: The browser receives and
interprets the response.
[Link]: The browser renders the content of the
response and displays it to the user.
3.3 What are Protocols?
Http (HyperText Transfer Protocol):
●Facilitates communication between a web browser and a server to
transfer web pages.
● Sends data in plain text (no encryption).
● Used for basic website browsing without security.
HTTPS (HyperText Transfer Protocol Secure):
●Secure version of HTTP, encrypts data for secure communication.
● Uses SSL/TLS to encrypt data.
●Used in online banking, e-commerce.
TCP (Transmission Control Protocol):
● Ensures reliable, ordered, and error-checked data delivery over the
● internet.
Establishes a connection before data is transferred.
3.4 Node Core Modules
[Link]-in: Core modules are included
with [Link] installation.
[Link] Installation Needed: Directly
available for use without npm
install.
[Link]: Highly optimized for
performance.
3.4 Node Core Modules
[Link] (File System): Handles file operations like reading and
writing files.
[Link]: Creates HTTP servers and makes HTTP requests.
[Link]: Launch a SSL Server.
[Link]: Provides utilities for handling and transforming file
[Link]: Provides operating system-related utility methods
and properties.
[Link]: Handles events and event-driven programming.
[Link]: Provides cryptographic functionalities like hashing and
encryption.
[Link]: Parses and formats URL strings.
3.5 Require Keyword
[Link]: Imports modules in [Link]. Syntax:
[Link]: Modules are cached after the const moduleName = require('module’);
first require call.
3..js is added automatically and is not
needed to at the end of module name.
[Link] Resolution: [Link] searches for
modules in core, node_modules, and file
paths.
3.6 Creating first Node Server
3.6 Creating first Node Server
3.6 Creating first Node Server

Run the code with:


node [Link]
3.6 Creating first Node Server
3.6 Creating first Node Server
Revision
•Click to edit Master text styles
1.H•oSewcon
•Third level
dD leNvelS Works?
[Link] •WFourthe
•Fifth levlebvel
eWlorks?
[Link] are Protocols?
[Link] Core Modules
5. Require Keyword
[Link] first Node Server
4. Request & Response

[Link] Lifecycle & Event Loop


[Link] to exit Event Loop
[Link] Request Object
[Link] Response
5. Routing Requests
[Link] User Input
7. Redirecting Requests
4.1 Node Lifecycle & Event Loop
4.2 How to exit Event Loop
4.3 Understand Request Object

[Link]
4.3 Understand Request Object

Use the browser to access:


[Link]
[Link]
4.4 Sending Response
4.4 Sending Response
4.5 Routing Requests
4.5 Routing Requests
4.5 Routing Requests
4.6 Taking User Input
4.7 Redirecting Requests
Practise Set
Create a page that shows a navigation bar of
Myntra with the following links:
A. Home B.
Men C.
Women D.
Kids E. Cart

Clicking on each link page should navigate to that


page and a welcome to section text is shown
there.
Revision
•Click to edit Master text styles
•Third levelecycle
1.N•oSedcoend Lleviefl & Event Loop
•Fifthhe
[Link] •tFoourt leveilt Event Loop
levxel
[Link] Request Object
[Link] Response
5. Routing Requests
[Link] User Input
7. Redirecting Requests
5. Parsing Request

1. Streams
2. Chunks
3. Buffers
[Link] Chunk
[Link] Chunks
[Link] Request
[Link] Modules
5.1 Streams
5.1 Streams
5.2 Chunks
5.2 Chunks
5.3 Buffers
5.4 Reading Chunk
5.5 Buffering Chunks
5.6 Parsing Request
5.6 Parsing Request
5.7 Using Modules
5.7 Using Modules
Practise Set
Create a Calculator
1. Create a new [Link] project named “Calculator”.
2. On the home page (route “/”), show a welcome message and a
3. link to the calculator page.
4. On the “/calculator” page, display a form with two input fields
and a “Sum” button.
When the user clicks the “Sum” button, they should be taken to
the “/calculate-result” page, which shows the sum of the two
numbers.
○ Make sure the request goes to the server.
○ Create a separate module for the addition function.
○ Create another module to handle incoming requests.
○ On the “/calculate-result” page, parse the user input, use
the addition module to calculate the sum, and display the
result on a new HTML page.
Revision
•Click to edit Master text styles
1.S•Stecroned alevmels
•Third level

[Link]•Fokurtsh level
•Fifth level

3. Buffers
[Link] Chunk
[Link] Chunks
[Link] Request
[Link] Modules
6. Event Loop
[Link] Driven
[Link] Threaded
3.V8 vs libuv
[Link] Runtime
[Link] Loop
[Link] Code
[Link] Code
6.1 Event Driven
6.2 Single Threaded
6.3 V8 vs libuv
V8:
[Link]-source JavaScript engine by Google.
[Link] in Chrome and [Link].
[Link] JavaScript to native machine
code.
[Link] high-performance JavaScript
execution.

libuv:
[Link]-platform support library for [Link].
[Link] asynchronous I/O operations.
[Link] event-driven architecture.
[Link] file system, networking, and
timers non-blockingly across platforms.
6.4 Node Runtime
6.4 Node Runtime
6.4 Node Runtime
6.4 Node Runtime
6.5 Event Loop
●timers: this phase executes callbacks
scheduled by setTimeout() and
setInterval().
●pending callbacks: executes I/O callbacks
deferred to the next loop iteration.
● idle, prepare: only used internally.
●poll: retrieve new I/O events; execute I/O
related callbacks (almost all with the exception
of close callbacks, the ones scheduled by
timers, and setImmediate()); node will block
here when appropriate. check: setImmediate()
● callbacks are invoked here.

●close callbacks: some close callbacks, e.g.


[Link]('close', ...).
6.5 Event Loop
6.6 Async Code
6.6 Async Code
6.7 Blocking Code
6.7 Blocking Code
Run & Observe
Blocking vs Async
const fs = require('fs');

[Link]('1. Start of script');

// Synchronous (blocking) operation


[Link]('2. Reading file synchronously');
const dataSync = [Link]('[Link]', 'utf8');
[Link]('3. Synchronous read complete');

// Asynchronous (non-blocking) operation


[Link]('4. Reading file asynchronously');
[Link]('[Link]', 'utf8', (err, dataAsync) => {
if (err) throw err;
[Link]('6. Asynchronous read complete');
});

[Link]('5. End of script');


Run & Observe
Event Loop Sequence
[Link]('1. Start of script');

// Microtask queue (Promise)


[Link]().then(() => [Link]('2. Microtask 1'));

// Timer queue
setTimeout(() => [Link]('3. Timer 1'), 0);

// I/O queue
const fs = require('fs');
[Link]('[Link]', () => [Link]('4. I/O operation'));

// Check queue
setImmediate(() => [Link]('5. Immediate 1'));

// Close queue
[Link]('exit', (code) =>
{ [Link]('6. Exit
event'); });

[Link]('7. End of script');


Revision

1.•CElick
•Sveceond
to edit
ltev
Master
eDlriven
text styles
•Third level
[Link]•Flouerth
•Fi fthTlevel
levhelreaded
3.V8 vs libuv
[Link] Runtime
[Link] Loop
[Link] Code
[Link] Code
7. NPM & Tools

[Link] Material Icons


[Link] init
[Link] Scripts
[Link] Packages
5. Installing Packages
[Link] nodemon
[Link] nodemon
7.1 Install Material Icons
7.2 npm init
npm init
7.3 npm Scripts
npm start
npm run khul-ja-sim-sim
7.4 npm Packages

[Link]: [Link] package manager for code sharing.


[Link]: Reusable code or library.
[Link]: Defines package metadata and
dependencies.
[Link]: Manages different package versions.
[Link]/Global: Install packages locally or globally.
[Link]: Public storage for open-source packages.
[Link]: Express, React, Lodash.
7.5 Installing Packages
npm install <package-name>

1.–save: Adds the package to the project’s dependencies in


[Link].
2.–save-dev: Adds the package to the project’s devDependencies
(used only in development) in [Link].
3.-g: Installs the package globally, making it available
system-wide, not just in a specific project.
4.–save-exact: Installs the exact version specified without
updating for newer versions.
5.–force: Forces npm to fetch and install packages even if they
are already installed.
7.6 Installing nodemon
npm install nodemon --save-dev

npm install
Recreates node_modules
7.7 Using nodemon

npm install nodemon -g


Revision
•Click to edit Master text styles

•Third levelaterial
1.I•nSescotnda llelv eMl Icons
•Fourth level

[Link] in•iFitfth level


[Link] Scripts
[Link] Packages
5. Installing Packages
[Link] nodemon
[Link] nodemon
8. Errors & Debugging

[Link] of Errors
[Link] Errors
[Link] Errors
4. Logical Errors
[Link] the Debugger
[Link] with Async Code
[Link] Debug with nodemon
8.1 Types of Errors

[Link] Error: An error in the code’s structure, causing it to


not compile or run (e.g., missing semicolon).
[Link] Error: The code runs but produces incorrect results
due to faulty logic (e.g., wrong formula).
[Link] Error: An error that occurs while the program is
running, often due to invalid operations
8.2 Syntax Errors
8.3 Runtime Errors
8.4 Logical Errors
8.5 Using the Debugger
Step 1 Step 3: Put a breakpoint

Step 2
8.5 Using the Debugger
Step 4: Use the tools Step 6: Debug Panel

Step 5: Hover
8.5 Using the Debugger
Step 7: Using Debug Console
8.6 Debugger with Async Code
8.7 Restart Debug with nodemon
Practise Set
Debug and fix Syntax, Runtime and Logical Errors
function calculateArea(width, height {
return width + height;
}

let width = 10 height = 5;

if (area > 100) {


[Link]("The area is large.");
} else {
[Link]("The area is small.");
}

if (width + height > 100) {


[Link]("Area is greater than or equal to 100");
}
Revision
•Click to edit Master text styles
1.T•Syecponed
•Third levelf
sle Errors
veol
[Link]•xFift h Eleverlrors
•Fourth level

[Link] Errors
4. Logical Errors
[Link] the Debugger
[Link] with Async Code
[Link] Debug with nodemon
9. Starting with [Link]

[Link] is [Link]
[Link] of [Link]
[Link] [Link]
[Link] Middleware
[Link] Response
[Link] DeepDive
[Link] Routes
9.1 What is [Link]
[Link] is a minimal and flexible
web application framework for
[Link].
[Link] provides a robust set of features
for building single-page,
multi-page, and hybrid web
applications.
[Link] simplifies server-side
coding by providing a layer of
fundamental web application
features.
9.2 Need of [Link]
[Link] Simplifies Server Creation: Helps in quickly
setting up and running a web server without the need for
complex coding.
[Link] Management: Provides a powerful routing
mechanism to handle URLs and HTTP methods
effectively.
[Link] Support: Allows the use of middleware to
handle requests, responses, and any middle operations,
making code modular and maintainable.
[Link] Development: Facilitates easy and efficient
creation of RESTful APIs.
[Link] and Plugins: Has a large ecosystem with
numerous plugins and extensions, accelerating
development time.
9.3 Installing [Link]
9.3 Installing [Link]
9.4 Adding Middleware
9.4 Adding Middleware
9.4 Adding Middleware
9.5 Sending Response
9.6 Express DeepDive
9.6 Express DeepDive
9.6 Express DeepDive
9.7 Handling Routes
9.7 Handling Routes
[Link] matters
[Link] not call next() after
send()
3.“/” matches everything
[Link] [Link] implicitly
calls [Link]()
9.7 Handling Routes
9.7 Handling Routes
Practise Set

Create a new project.


1. Install nodemon and express.
2. Add two dummy middleware that logs request path
and request method respectively.
3. Add a third middleware that returns a response.
4. Now add handling using two more middleware that
handle path /, a request to /contact-us page.
5. Contact us should return a form with name and email
as input fields that submits to /contact-us page also.
6. Also handle POST incoming request to /contact-us
path using a separate middleware.
Revision

•Second
1.•CWlick letve
hto lisMaster
aedit
•Third level
[Link]
text styles
•F iftohlevel
[Link]•Fdourth lefvel [Link]
[Link] [Link]
[Link] Middleware
[Link] Response
[Link] DeepDive
[Link] Routes
10. [Link] DeepDive

[Link] Requests
[Link] Router
[Link] 404
[Link] Paths
[Link] HTML Files
[Link] HTML Files
[Link] File Helper
10.1 Parsing Requests
10.2 Express Router
10.2 Express Router
10.2 Express Router
10.3 Adding 404
10.4 Common Paths

or
10.5 Adding HTML Files
10.6 Serving HTML Files
10.7 Using File Helper
Practise Set

Reuse the app from the last assignment


1. Parse the body of the contact-us request and log it to
console.
2. Move the code to separate local modules and use the
Express router to import and use them in [Link]
3. Move all the html code to html files and serve them
using the file helper.
4. Also add a 404 page for this app.
Revision

•Secronsd
1.•CPlicak lienvelg
to edit
•Third level
Requests
Master text styles
[Link]•rFourth
•eFiftshlevel
lesvel Router
[Link] 404
[Link] Paths
[Link] HTML Files
[Link] HTML Files
[Link] File Helper
11. Styling using

[Link] Static Files


[Link] to Tailwind CSS
[Link] Classes
[Link] Extension
[Link] Tailwind CSS
[Link] Tailwind CSS
[Link] Tailwind CSS
[Link] Tailwind Automatically
11.1 Serving Static Files
11.1 Serving Static Files
11.2 Introduction to Tailwind CSS
1. Responsive: Mobile-first design for all device sizes.
2. Utility-First: Provides low-level utility classes for
building custom designs.
3. Highly Customizable: Easily extendable through a
config file.
4. Responsive Design: Built-in responsive utilities (e.g.,
sm:, md:).
5. No Predefined Components: Focuses on building
custom components.
6. Purge CSS: Removes unused styles in production for
smaller files.
7. Fast Development: Style elements directly in markup
for speed.
11.3 Utility Classes
11.4 Installing Extension
11.4 Installing Extension
11.5 Including Tailwind CSS
11.6 Installing Tailwind CSS

1. Install:
npm init -y
npm install -D tailwindcss postcss autoprefixer
2. Initialize Tailwind CSS Config
npx tailwindcss init
11.6 Installing Tailwind CSS
Configure Tailwind in the Configuration Files ([Link])
11.6 Installing Tailwind CSS

Add Tailwind Directives to views/[Link]


11.6 Installing Tailwind CSS

5. Include public/[Link] into your [Link]


6. Run Command
npx tailwindcss -i ./views/[Link] -o ./public/[Link] --watch
7. Declare Shortcut:

8. Run Command
npm run tailwind
11.7 Using Tailwind CSS
11.8 Building Tailwind Automatically
Practise Set

Style other page using


Tailwind.
Revision

•Scond tro
1.•CSlicek levnelg Static
evdiit
•Third level
MasterFiles
text styles
•Fidfthlevel
[Link]•rFoourth luevecltion to Tailwind CSS
[Link] Classes
[Link] Extension
[Link] Tailwind CSS
[Link] Tailwind CSS
[Link] Tailwind CSS
12. Dynamic UI using EJS

[Link] of Dynamic UI
[Link] using Global Variables
[Link] is EJS
[Link] EJS
[Link] EJS Templates
[Link] with Partials
12.1 Need of Dynamic UI
●Personalized Content: Tailors responses based on user
profiles, preferences, or behaviors to enhance user
experience.
●Dynamic Data Delivery: Provides real-time information
that updates with each request, such as live scores or
stock prices.
●Security and Access Control: Delivers different content
based on user authentication and authorization levels.
●Localization and Internationalization: Adjusts
responses to accommodate different languages, cultures,
or regional settings.
●API Versatility: Supports multiple client types (web,
mobile, IoT) by providing appropriate data formats and
structures.
12.2 Sharing using Global Variables

Variables are shared across


users
12.3 What is EJS
●HTML with JS: EJS lets you embed JavaScript
code within HTML.
●Simple Syntax: Uses <% %> for control flow and
<%= %> for output.
●Easy to Learn: Familiar to those who know
HTML and JavaScript.
●Template Reuse: Supports partials for reusing
code snippets.
●Flexible Logic: Allows full JavaScript expressions
in templates.
12.4 Installing EJS
12.4 Installing EJS
12.5 Using EJS Templates
12.6 Working with Partials
12.6 Working with Partials
12.6 Working with Partials
12.6 Working with Partials
Practise Set

Reuse the app from the last assignment


1. Add more fields in the add home page like price per
2. night, location, rating, photo.
3. Design the home card to show all of this information
Make the selected tab active on top.
Revision

1.•CNlicke
•Scond level toe
Dtexyt
eddit
sntylaesmic
Moasfte r UI
•iFinfth gleve lusing Global Variables
•Third level

[Link]•Frourth level
[Link] is EJS
[Link] EJS
[Link] EJS Templates
[Link] with Partials
13. Model View Controller
[Link] of Concerns
[Link] First Controller
[Link] All Controllers
[Link] 404 Controller
[Link] Models
[Link] data to Files
[Link] causing problems
[Link] data from Files
13.1 Separation of Concerns
● MVC stands for Model-View-Controller: A
software architectural pattern for developing
user interfaces.
●Model: Manages the data and business logic
of the application.
●View: Handles the display and presentation
of data to the user.
●Controller: Processes user input, interacts
with the Model, and updates the View
accordingly.
●Routes are a part of Controllers.
●Purpose: MVC separates concerns within an
application, making it easier to manage and
scale.
13.2 Adding First Controller
13.3 Adding All Controllers
13.3 Adding All Controllers
13.3 Adding All Controllers
13.4 Adding 404 Controller
13.5 Adding Models
13.5 Adding Models
13.6 Writing data to Files
13.6 Writing data to Files
13.7 Nodemon causing problems
13.8 Reading data from Files
13.8 Reading data from Files
Practise Milestone

Take your airbnb forward:


1. Structure the views folder into host & store and move the
2. respective view files there.
Add more views to store like: home-list, home-detail,
favourite-list, reserve, bookings. And to host view:
edit-home, host-home-list
3. Improve the header with navigation to all pages.
4. Register all the new routes and add dummy views there.
5. Change controllers to store and host setup.
6. Add Edit and Delete buttons to the host-home-list view.
7. Keep the logic for Edit, Delete, Favourite pending.
Revision

1.•SClicek
•Second level
pto aedrit aMatstieor tnex to stfyle sCo
•iFonurthg
[Link]•Tdhird level lev elFirst Controller
3. Adding All Controllers
•Fifth level

[Link] 404 Controller


[Link] Models
[Link] data to Files
[Link] causing problems
[Link] data from Files
14. Dynamic Path & Model deep-dive

[Link] are dynamic paths


2. Adding Home Details Page
3. Showing Real Home Data
4. Adding Favourites Feature
[Link] Favourites Model
6. Edit-Home: Adding Feature Skeleton
7. Edit-Home: Showing Existing Data
8. Edit-Home: Handing Edit Request
9. Adding Delete Feature
10. Removing Home from Favourites
14.1 What are dynamic paths

●Path parameters are variables embedded directly in the URL


path to capture dynamic values, like /users/:userId where :userId
is replaced with a specific user ID.
●Query parameters are key-value pairs appended to the URL after
a ?, used to send additional data, like /search?query=nodejs
where query=nodejs specifies the search term.
14.2 Adding Home Details Page
[Link] a details button in /homes-list to go to link path /homes/:home-id
[Link] a random id to each home in the data file.
[Link] a random id on home object before saving in the home model.
[Link] a route in the store router for /homes/:home-id
[Link] a method in store controller to get the home-id using [Link]
and log it, before sending out a dummy response with home id.
14.2 Adding Home Details Page
1.

2.

3.
14.2 Adding Home Details Page
4.

5.
14.3 Showing Real Home Data
[Link] a static findById method in Home model that takes a callback.
[Link] this findById method in the controller to load home details and log
them.
[Link] change the controller:
a. Redirect to /homes in case the home is not found, logging an error.
b. Rendering the /home-detail page with home data.
4. Create a home-detail page to use the entire page to show all home data.
5. Download from Github:
a. The styled home-detail file.
b. 10 image of homes that you can put locally and use.
14.3 Showing Real Home Data
1.

2.
14.3 Showing Real Home Data
3.
14.3 Showing Real Home Data
4. 5.
14.4 Adding Favourites Feature
[Link] a partial with a form and a button that submits to /favourites path

with a hidden input having home-id value.


[Link] this partial to home-detail page
[Link] this partial to home-list page.
[Link] router for handling POST request to /favourites path.
[Link] a method in store controller to add a home id as favourites, logging
the id for now, before redirecting to /favourites path.
14.4 Adding Favourites Feature
1.

2.
14.4 Adding Favourites Feature
3.
14.4 Adding Favourites Feature
4.

5.
14.5 Adding Favourites Model
1. Create a new Model to handle Favourites:
a. A static method getFavourites that reads the [Link] file and
b. return the ids of all homes marked favourite.
A static method addFavourites that adds the home-id to favourites-id
array if not already there, then updates the file.
2. Use this model in addFavourites controller.
3. Use this model in getFavourites controller while also fetching details of
4. all homes from Homes Model.
Change the UI of favourites page to show new content.
14.5 Adding Favourites Model
1.
14.5 Adding Favourites Model
2.
14.5 Adding Favourites Model
3.
14.5 Adding Favourites Model
4.
14.6 Edit-Home:
Adding Feature Skeleton

[Link] the [Link] to [Link]


[Link] it’s usage in the add-home controller.
[Link] the path of edit button everywhere.
[Link] a new router for GET /edit-home/:home-id
[Link] a new controller method in host controller, optionally logging
query param of editing=true, while passing editing flag to view.
14.6 Edit-Home: Adding Feature Skeleton

1.

2.
14.7 Edit-Home: Showing Existing Data

3.
14.6 Edit-Home: Adding Feature Skeleton

4.

5.
14.7 Edit-Home:
Showing Existing Data
[Link] the controller to now fetch the home details, if not found
redirect to /host/host-home-list otherwise passing the data to view.
[Link] the [Link] to show dynamic content based on values:
a. Different submit path.
b. Different button text.
c. Pre-filled values if present.
14.7 Edit-Home: Showing Existing Data

1.
14.7 Edit-Home: Showing Existing Data
2.
14.8 Edit-Home:
Handing Edit Request
1. Add a router for POST /edit-home
2. Add a controller for /edit-home, which creates a home model object
3. and saves it, before redirecting to /host/host-home-list
4. Add hidden id input field in the [Link] to get the id as part of
POST request.
Change the save method in Model to handle creation of new as well
as updation of existing Home.
14.8 Edit-Home: Handing Edit Request
1.

2.

3.
14.8 Edit-Home: Handing Edit Request
4.
14.9 Adding Delete Feature
[Link] the delete button with a form that submits to path
/host/delete-home/:homeId
[Link] a route in the host routes.
[Link] a static delete method to the Home model that takes an id and deletes
the home.
[Link] a method in host controller to handle the request, delete the home and
redirect to /host/host-homes-list page.
[Link]: deleted homes might still be in favourites list.
14.9 Adding Delete Feature
1.

2.

3.
14.9 Adding Delete Feature
4.
14.10 Removing Home from Favourites
[Link] a static method to the favourites model to delete the hom
[Link] a form to the favourites-list in each home to path
/favourites/delete/:homeId
[Link] a route for POST delete-favourites in the store routes.
[Link] a method in store controller to use the model’s static method and then
redirect to favourites-list.
[Link] this model method in home-delete to make sure any deleted home is
also removed from favourites.
14.10 Removing Home from Favourites
1.

2.

3.
14.10 Removing Home from Favourites
4.

5.
Revision
1.•WClichk atot eadirt eM adstyenr taemxt iscty lpeasths
2. A•dSedcond
•Tihnirdglevel
le vHelome Details Page
3. Show•iFnougrth
•FiftRh leeveall
level Home Data
4. Adding Favourites Feature
[Link] Favourites Model
6. Edit-Home: Adding Feature Skeleton
7. Edit-Home: Showing Existing Data
8. Edit-Home: Handing Edit Request
9. Adding Delete Feature
10. Removing Home from Favourites
15. Introduction to SQL

[Link] is a DB (Database)
[Link] to SQL DB
[Link] to NoSQL DB
[Link] vs NoSQL
[Link] MySQL
6. Connecting App to DB
7. Creating homes Table
[Link] homes in App
[Link] DB in Models
[Link] Home in Model
[Link] Model using Where
15.1 What is a DB (Database)
1. Store Data: Keep large amounts of data in a structured format.
2. Enable Data Management: Allow for adding, updating, and deleting
data easily.
3. Facilitate Quick Access: Provide fast retrieval of data through
queries.
4. Ensure Data Integrity: Maintain accuracy and consistency of data
over time.
5. Support Multiple Users: Handle concurrent access by many users
simultaneously.
6. Secure Data: Protect information through access controls and
authentication.
15.2 Introduction to SQL DB
● Vertical Scalability: Typically scaled
by increasing the resources of a single
server (scaling up).
● Relationships: Tables can have
multiple types of relationships.

● Relational Model: Organize data into tables with rows and


columns.
● Fixed Schema: Require a predefined schema; the structure of
the data must be known in advance.
15.2 Introduction to SQL DB
● Relational Model Use of SQL: Utilize SQL for
querying and managing data, which is a
standardized and widely-used language.
● ACID Compliance: Support transactions that are
Atomic, Consistent, Isolated, and Durable.
● Complex Queries: Excel at handling complex
queries and relationships between data.
15.3 Introduction to NoSQL DB
● Flexible Schema: Allow for dynamic schemas,
accommodating unstructured or semi-structured
data without predefined structures. Duplicacy
over Relations: Duplicates data across records
● (denormalization) to enhance performance and
scalability, rather than relying on complex
relationships and joins as in relational
databases. Horizontal Scalability: Designed to
scale out by adding more servers, handling large
● volumes of data efficiently. Performance:
Optimized for high throughput and low latency,
suitable for real-time applications.

15.4 SQL vs NoSQL
15.4 SQL vs NoSQL
15.5 Installing MySQL
15.5 Installing MySQL
15.5 Installing MySQL
15.5 Installing MySQL
15.5 Installing MySQL
15.6 Connecting App to DB
15.7 Creating homes Table
15.7 Creating homes Table
15.7 Creating homes Table
15.8 Querying homes in App
15.9 Adding DB in Models
[Link] the test code from [Link]
[Link] the [Link] model file to remove all code related to file operations.
[Link] the DB from the utils.
[Link] photoUrl to imageUrl and houseName to name in the entire project.
[Link] fetchAll:
a. Using the query we used while testing.
b. fetchAll will not take a callback but return a promise.
6. Go to StoreController and use the promise to get the data here.
7. Fix all the usages of fetchAll.
15.9 Adding DB in Models
2,3.
15.9 Adding DB in Models
5.

6.
15.9 Adding DB in Models
7.
15.10 Adding Home in Model
[Link] the description field in home. Change constructor and usag
[Link] changes in UI to input and show it everywhere.
[Link] the save method using the insert query.
[Link] the usages of save method to use the promise.
15.10 Adding Home in Model
1.
15.10 Adding Home in Model
2.
15.10 Adding Home in Model
3.

4.
15.11 Implementing Model using Where
Practise Milestone

Take your airbnb forward:


● Change the save method to support both edit and insert
functionality.
Practise Milestone (Solution)
Practise Milestone (Solution)
Revision

1.•WClichka tto eisdi ta M DasBte r( tDexatt satybleasse)


[Link]•Stercond levellecvetlion to SQL DB
•Tohidrdu
•cFiftthi
[Link]•dFouurth levelloevnel to NoSQL DB
[Link] vs NoSQL
[Link] MySQL
6. Connecting App to DB
7. Creating homes Table
[Link] homes in App
[Link] DB in Models
[Link] Home in Model
[Link] Model using Where
16. Introduction to MongoDB
[Link] is MongoDB
[Link] up MongoDB
[Link] MongoDB Driver
[Link] MongoDB Connection
[Link] a Home [Link]
MongoDB Compass [Link]
MongoDB for VSCode [Link]
all Homes [Link] one Home

10. Supporting Edit & Delete


[Link] MongoDB to Favourite
16.1 What is MongoDB
1. MongoDB is the product and the company that builds it.
[Link] name comes from the work Humongous.
3. NoSQL Document Database: Stores data in flexible, JSON-like
documents.
4. Dynamic Schema: Allows fields to vary across documents without
predefined schemas.
5. High Performance: Optimized for fast read and write operations.
6. Scalability: Supports horizontal scaling through sharding.
7. High Availability: Provides replication with automatic failover.
8. Rich Query Capabilities: Offers powerful querying, indexing, and
aggregation.
9. Geospatial and Text Search: Includes support for location-based
and full-text queries.
10. Cross-Platform Compatibility: Works with various operating
systems and programming languages.
Easy Integration: Integrates smoothly with modern development
11.
stacks.
16.2 Setting up MongoDB

VS
16.2 Setting up MongoDB
16.2 Setting up MongoDB
16.2 Setting up MongoDB
16.2 Setting up MongoDB
16.3 Installing MongoDB Driver
16.3 Installing MongoDB Driver
16.3 Installing MongoDB Driver
16.3 Installing MongoDB Driver
16.4 Creating MongoDB Connection
16.5 Saving a Home
16.6 Install MongoDB Compass
16.6 Install MongoDB Compass
16.6 Install MongoDB Compass
16.6 Install MongoDB Compass
16.6 Install MongoDB Compass
16.6 Install MongoDB Compass
16.7 Install MongoDB for VSCode
16.7 Install MongoDB for VSCode
16.7 Install MongoDB for VSCode
16.7 Install MongoDB for VSCode
16.7 Install MongoDB for VSCode
16.8 Fetching all Homes
1. Basic Usage: [Link](query) retrieves
documents matching the query criteria.
2. Returns a Cursor: The method returns a
cursor, an iterator over the result set.
16.8 Fetching all Homes
16.9 Fetching one Home
16.9 Fetching one Home
16.9 Fetching one Home
16.9 Fetching one Home
16.10 Supporting Edit & Delete
16.11 Adding MongoDB to Favourite
[Link] all the file handling related code from Favourite Model.
[Link] the data folder.
[Link] the following methods in Favourite model to use mongo:
a. fetchAll
b. Change addToFavourites to save method
c. deleteById
[Link] the usages of Favourite model in StoreController to use the promise syntax
a. getFavourites
b. postAddFavourites
c. postRemoveFavourite
16.11 Adding MongoDB to Favourite

1. 2.
16.11 Adding MongoDB to Favourite

3.
16.11 Adding MongoDB to Favourite

4.a.
16.11 Adding MongoDB to Favourite

4.b.
16.11 Adding MongoDB to Favourite

4.c.
Practise Milestone

Take your airbnb forward:


● Change the favourite model to fix the problem of having
duplicate favourite records.
Practise Milestone (Solution)
Revision
1.•WClichk atot eidsit Masotenrg toexDt sBtyles
•tThiinrd
2.S•eStecond glev eulp MongoDB
level
•nFifgth
[Link]•lFloiurth leMvelongoDB Driver
level
[Link] MongoDB Connection
[Link] a Home [Link]
MongoDB Compass [Link]
MongoDB for VSCode [Link]
all Homes [Link] one Home

10. Supporting Edit & Delete


[Link] MongoDB to Favourite
17. Introduction to Mongoose

[Link] is Mongoose
[Link] up Mongoose
[Link] Home Schema
[Link] Home using Mongoose
5. Fetching Homes
[Link] one Home
[Link] a Home
[Link] a Home
[Link] Mongoose for Favourite
10. Fetching Relations
17.1 What is Mongoose

[Link] is an Object Data Modeling (ODM) library for MongoDB and [Link].
[Link] a schema-based solution to model application data.
[Link] data validation and type casting in [Link] applications.
[Link] easy interaction with MongoDB through intuitive methods.
[Link] middleware for pre and post-processing of data.
[Link] manage relationships between data with built-in functions.
17.2 Setting up Mongoose
17.2 Setting up Mongoose
[Link] Mongoose package.
[Link] and use mongoose in [Link]
[Link] the database-util file.
[Link] the usage of db-util from everywhere.

1.
17.2 Setting up Mongoose

2.
17.3 Create Home Schema
[Link] complete airbnb db from mongo.
[Link] the existing Home Model code.
[Link] the new Home Schema in the Home Model File.
17.4 Saving Home using Mongoose
17.5 Fetching Homes
17.6 Fetching one Home

It already works !!!


17.7 Editing a Home
17.8 Deleting a Home
17.9 Using Mongoose for Favourite
[Link] the existing Favourite Model code.
[Link] the new Favourite Schema in the Favourite Model File.
[Link] the following functionalities:
a. Getting all Favourite
b. Adding A Favourite
c. Deleting a Favourite
4. Removing Favourite while removing home.
17.9 Using Mongoose for Favourite

1, 2.
17.9 Using Mongoose for Favourite

3.a.
17.9 Using Mongoose for Favourite

3.b.
17.9 Using Mongoose for Favourite

3.c.
17.9 Using Mongoose for Favourite

4.
17.10 Fetching Relations
Revision
1.•WClichk atot e disit Masotenr gteoxto sstyeles
2.S•eSetctonidn
•Third levelp
lgevMongoose
eul
[Link]•Feou rtHh
•Fifth levoel Schema
levmele
[Link] Home using Mongoose
5. Fetching Homes
[Link] one Home
[Link] a Home
[Link] a Home
[Link] Mongoose for Favourite
10. Fetching Relations
18. Cookies & Sessions

[Link] are Cookies


[Link] Login Functionality
3. Checking Login State
[Link] a Cookie
[Link] the Logout Feature
[Link] with Cookies
[Link] are Sessions
8. Installing Session Package
9. Creating a Sessions
[Link] Session in DB
18.1 What are Cookies

[Link] are small pieces of data stored in the user’s browser by


server.
[Link] help websites remember user information and preferences
between page loads or visits.
[Link] can manage user sessions and store data for personalized
experiences.
18.1 What are Cookies
18.2 Adding Login Functionality
[Link] a login button to the nav bar pointing to /login
[Link] a auth router to handle login related routes, register the
new router in [Link]
[Link] a auth controller to handle GET request for /login and
return a UI that does the following:
a. Accepts email and password
b. Has a Login button that submits the form to /login with a
POST request.
4. Add a POST login path in router and handler in controller.
5. Assume the person logged in and redirect them to the home page.
18.2 Adding Login Functionality

1.
18.2 Adding Login Functionality

2.
18.2 Adding Login Functionality

3.
18.2 Adding Login Functionality

3.
18.2 Adding Login Functionality

4, 5.
18.3 Checking Login State
[Link] a isLoggedIn field in the req object and use it everywhere
else.
[Link] a condition in the navigation ejs file that no path other
than home and login should be visible until a user has logged in.
[Link] all the render calls to send the flag
[Link] add a middleware for host routes that if the user is not
logged in they should be redirected to the login page.
18.3 Checking Login State

1.
18.3 Checking Login State

2.
18.3 Checking Login State

3.
18.3 Checking Login State

4.
18.4 Using a Cookie
[Link] why a global variable would not work.
[Link] a cookie on successful login. See it in storage, also on the
next request.
[Link] the cookie using syntax and Define a middleware to set
this value to the request object.
[Link]([Link]('Cookie').split('=')[1]);

[Link] the Cookie from the browser and see the result.
18.4 Using a Cookie

2.

3.
18.4 Using a Cookie

4.
18.5 Define the Logout Feature
[Link] a logout button in nav bar that should come only when
user is logged in. Button should be a form that submits to link
/logout.
[Link] the login button in case user is logged in.
[Link] the logout path and set the isLoggedIn cookie to false.
18.5 Define the Logout Feature

1, 2.
18.5 Define the Logout Feature

3.
18.6 Problem with Cookies
[Link] can be intercepted or stolen, posing
security risks.
[Link] have limited storage capacity (about
4KB).
[Link] can delete or modify cookies, leading
to data loss or tampering.
[Link] in cookies is not encrypted, making
sensitive information vulnerable.
[Link] important info in cookies exposes it
to client-side attacks.
18.7 What are Sessions

[Link] are server-side storage mechanisms that track user


interactions with a website.
[Link] maintain user state and data across multiple requests in a
web application.
[Link] enable persistent user experiences by maintaining state
between the client and server over stateless HTTP.
18.8 Installing Session Package
18.8 Installing Session Package
18.9 Creating a Session
[Link] info is stored on server.
[Link] session is valid for all requests from one user, using
cookies.
[Link] setting the cookie and now save the flag in session.
[Link] the browser for cookie changes.
[Link] Session in some get request.
[Link] to use a different browser and show that session is
different.
[Link] are stored in memory so they reset when server
restarts.
18.9 Creating a Sessions

3.

4.
18.9 Creating a Sessions

5.
18.10 Saving Session in DB
18.10 Saving Session in DB
Practise Milestone

Take your airbnb forward:


●Cleanup cookie code to use session everywhere.
●Remove the cookie middleware.
●Destroy the session on logout.
●Cleanup Logs.
●Understand why leaving the cookie on logout is fine.
Practise Milestone (Solution)
Revision
1.•CWlickh toa etd iat Mraes teCr oteoxkt siteylses
•dThiirdn
2.A•Sdecond legve lLogin Functionality
level
3. Chec•Fkourth
•iFnifthglevel
le vLelogin State
[Link] a Cookie
[Link] the Logout Feature
[Link] with Cookies
[Link] are Sessions
8. Installing Session Package
9. Creating a Sessions
[Link] Session in DB
19. Authentication & Authorization
[Link] is Authentication
[Link] is Authorization
[Link] based Authentication
[Link] vs Authorization
[Link] UI
[Link] Express Validator
[Link] User Model
8. Encrypting Password
[Link] Login
[Link] User Functions
19.1 What is Authentication

[Link] is the process of verifying the identity of a user or


system accessing an application.
[Link] ensures that only authorized users can access protected
resources and features.
[Link] is crucial for security, protecting data, and
providing personalized experiences in web applications.
19.2 What is Authorization
[Link] is the process of determining
what actions a user is permitted to
perform within an application.
[Link] ensures that users can access only the
resources and functionalities they have
permission for.
[Link] enhances security by
restricting access to sensitive data and
operations, complementing the
authentication process.
19.3 Session based Authentication
19.4 Authentication vs Authorization
19.4 Authentication vs Authorization
19.5 Signup UI
[Link] a signup button in navigation bar along with sign-in. It should
point to a link /signup
[Link] a auth/[Link] file that has the following fields and
submits POST request to /signup:
[Link], lastName,
b. email
[Link], confirmPassword
[Link] with possible values ‘guest’, ‘host’
[Link] and conditions checkbox.
[Link] routes in authRouter and behaviour in authController.
[Link] the UI of the app to look pretty.
19.5 Signup UI

1.
19.5 Signup UI
2.
19.5 Signup UI

3, 4.
19.6 Using Express Validator
[Link] handling for POST /signup in auth controller and router.
[Link] Express Validator.
[Link] the email and password validations in the post handler.
[Link] the [Link] to show the errors. And accept the old
values.
19.6 Using Express Validator
1.

2.
19.6 Using Express Validator
3.
19.6 Using Express Validator
3.
19.6 Using Express Validator
4.
19.7 Adding User Model
[Link] a new User Model with following fields:
[Link] & lastName (required)
[Link] (required, unique)
[Link] (required)
[Link] (possible values ‘guest’, ‘host’)
[Link] the POST signup handler, create a new user with the fields
from request and redirect to login after saving the user.
19.7 Adding User Model
1.
19.7 Adding User Model
2.
19.8 Encrypting Password
[Link] the problem with plain text passwords.
[Link] a package named: bcryptjs
[Link] the password before saving password.
[Link] that even server does not have the password.
19.8 Encrypting Password
2.
19.8 Encrypting Password
3.
19.9 Implementing Login
[Link] the email and password from the request body and
find the user with the email from the Users collection.
[Link] the user is not found send an error and re-render the
login page, also make changes to the login page to show
errors.
[Link] the user is found, then use the bcrypt compare function
to match the entered password, If password does not
match send another error, otherwise create a login session
and redirect user to the home.
19.9 Implementing Login
1.
19.9 Implementing Login
2.
19.9 Implementing Login
3.
19.10 Adding User Functions
[Link] the navigation bar items display only on the basis of userType by
passing the user object to all views.
[Link] a field in User Model names favouriteHomes, which is an array of
home ids.
[Link] the Favourite Model and the Pre hook from the Home Model.
[Link] the favourite user specific and change the following methods:
a. postAddFavourites
b. getFavourites
c. postRemoveFavourite
19.10 Adding User Functions
1.
19.10 Adding User Functions
2.
19.10 Adding User Functions
4.a.
19.10 Adding User Functions
4.b.
19.10 Adding User Functions
4.c.
Revision
1.•WClichk atot e diist MAasutetr htextn styilcesation
•aThtird
2.W•Shecond liesve lAuthorization
level
•nFi ftbh
[Link]•ioFourth levelleavesled Authentication
[Link] vs Authorization
[Link] UI
[Link] Express Validator
[Link] User Model
8. Encrypting Password
[Link] Login
[Link] User Functions
20. File Upload & Download

[Link] a File Picker


[Link] Multipart Form
[Link] Multipart Form Data
[Link] Image Files [Link]
File Names [Link] Upload
File Types [Link] Edits
[Link] Saved Data [Link]
Files after Auth

[Link] Files
20.1 Adding a File Picker

●Input Element: Use <input type="file"> to create


a file picker.
●Multiple Files: Add multiple attribute to allow
selecting multiple files.
●File Types: Use accept attribute to restrict file
types (e.g., accept=".jpg, .png").
20.2 Creating Multipart Form
20.3 Handling Multipart Form Data
20.3 Handling Multipart Form Data
20.4 Saving Image Files
20.5 Custom File Names
20.6 Restricting Upload File Types

Adding this filter, now multer would not have the file
if it does not match the type and [Link] will just be
undefined.
20.6 Restricting Upload File Types
20.7 Handling Edits

While editing we can make sure that we only overwrite the photoUrl in
case a new valid image was uploaded. And don’t force the user to upload
images each time they edit.
20.8 Serving Saved Data

This is done as like in case of public, things inside


public will be served like they are in root folder and
the url does not have public in it. Here also either
remove uploads/ from the image path, or add the
qualifier.
20.9 Serving Files after Auth
20.9 Serving Files after Auth
20.10 Deleting Files
Revision
1.•CAlicdkd toi nedgit aM aFsteilre te xPti sctyklesr
•Third level
2.C•rSeecoantd Multipart Form
ilenvgel
•Fifthlevelultipart
[Link]•Floiunrthg le veMl Form Data
[Link] Image Files
[Link] File Names
[Link] Upload File Types
[Link] Edits
[Link] Saved Data
[Link] Files after Auth
[Link] Files
21. REST API / JSON Requests
[Link] are Async Requests
[Link] are REST APIs
3. Decoupling Frontend & Backend
[Link] & HTTP Methods
5. REST Core Concepts
6. First API Todo App
[Link] for Fetch Items
[Link] for Deleting Items
[Link] UI Elements
[Link] Complete Item functionality
11. Deploying React App
21.1 What are Async Requests

●Async network requests enable web pages to communicate with


servers without reloading.
●The client sends JSON requests to the server asynchronously in
single-page apps.
●The server processes the request and returns a JSON response.
●The page updates itself dynamically using the received data.
21.2 What are REST APIs

●REST APIs enable communication between clients and servers using HTTP.
●They are mainly identified by a URI.
●They use standard HTTP methods like GET, POST, PUT, and DELETE.
●Data is exchanged in formats like JSON or XML.
● REST APIs are stateless.
●REST APIs allow clients to access and manipulate web resources.
21.3 Decoupling Frontend & Backend

●Separating front-end and back-end allows independent development and


scaling.
●REST APIs serve as a communication layer between them.
● Front-end interacts with back-end through standardized RESTful calls.
●Decoupling enhances flexibility and simplifies maintenance.
● REST APIs enable front-end updates without altering back-end code.
21.4 Routes & HTTP Methods
● REST API routes define the endpoints (URLs)
where resources can be accessed by clients.
●GET: Retrieves data from the server at the specified
route.
●POST: Sends new data to the server to create a
resource.
● PUT: Updates or replaces an existing resource at a
given route.
●DELETE: Removes a resource from the server at
the specified route.
● PATCH: Partially updates an existing resource with
new data.
21.5 REST Core Concepts

●Statelessness: Each request contains all necessary information; the server maintains no
client session.
●Uniform Interface: Standardized communication using HTTP methods like GET, POST, PUT,
DELETE.
●Client-Server Separation: Independent development of front-end and back-end components.
●Cacheability: Responses indicate if they can be cached to improve performance.
●Layered System: Architecture allows for multiple layers between client and server.
●Code on Demand (Optional): Servers can extend client functionality by sending executable
code.
21.6 First API Todo App
[Link] the following from the previous app:
a. Env files
b. Package dependencies
c. [Link]
2. Changes in env files
a. Remove the email data.
b. Change DB name to todo-app
[Link] empty controllers, models, and routes folders.
[Link] excess code from [Link].
[Link] the error controller to give out a 404 error message and status.
[Link] a Mongoose model for TodoItem.
[Link] itemsRouter and itemsController for POST /todos request from frontend.
[Link] and setup CORS package in backend.
9. Add [Link]() to app.
21.6 First API Todo App
1.

3.

2.
21.6 First API Todo App
4.
21.6 First API Todo App
6.
5.
21.6 First API Todo App
7.
21.6 First API Todo App

8,9.
21.7 API for Fetch Items
21.8 API for Deleting Items
21.9 Improving UI Elements

[Link] bootstrap
[Link] tailwind to the project.
[Link] the whole app using tailwind classes.
21.10 Adding Complete Item functionality

[Link] a UI element to mark the item complete.


[Link] a component state based on which items will be striked through, default
value should come from server.
[Link] a toggleComplete handler in TodoItem that sends a PATCH request to
update the completed flag and expects the updated item in return. Also the
value of state must be updated based on the final value.
[Link] a route and API in the backend to update the todoItem.
21.10 Adding Complete Item functionality
1,2.
21.10 Adding Complete Item functionality
3.
21.10 Adding Complete Item functionality

4.
Revision
1.•WClichk taot e daitr Meas tAer steyxnt scty lResequests
•aThitrd
2.W•Shecond leaverle REST APIs
level
•Flifithnlevel
[Link]•uFouprth legvel Frontend & Backend
[Link] & HTTP Methods
[Link] Core Concepts
[Link] API Todo App
[Link] for Fetch Items
[Link] for Deleting Items
[Link] UI Elements
[Link] Complete Item functionality

You might also like