Module 5
Module 5
React Introduction
If you have npx and [Link] installed, you can create a React application by using
create-react-app.
If you've previously installed create-react-app globally, it is recommended that you uninstall the
package to ensure npx always uses the latest version of create-react-app.
The create-react-app will set up everything you need to run a React application.
Now you are ready to run your first real React application!
cd my-react-app
npm start
A new browser window will pop up with your newly created React App! If not, open your
browser and type localhost:3000 in the address bar.
In this example:
● import React from 'react': Imports React to create components and use JSX.
● function App() { ... }: Defines a functional component called App.
● return ( ... ): Returns JSX that represents the UI (a div with an h1 tag displaying
"Hello, World!").
● export default App: Exports the App component so it can be used elsewhere.
React operates by creating an in-memory virtual DOM rather than directly manipulating the
browser’s DOM. It performs necessary manipulations within this virtual representation
before applying changes to the actual browser DOM.
Module-5 Back-End Integration and Deployment:
● Initially, there is an Actual DOM(Real DOM) containing a div with two child
elements: h1 and h2.
● React maintains a previous Virtual DOM to track the UI state before any updates.
2. Detecting Changes
● When a change occurs (e.g., adding a new h3 element), React generates a New
Virtual DOM.
● React compares the previous Virtual DOM with the New Virtual DOM using a
process called reconciliation.
● React identifies the differences (in this case, the new h3 element).
● Instead of updating the entire DOM, React updates only the changed part in the
New Actual DOM, making the update process more efficient.
React is one of the most demanding JavaScript libraries because it is equipped with a ton of
features which makes it faster and production-ready. Below are the few features of React.
1. Virtual DOM
React uses a Virtual DOM to optimize UI rendering. Instead of updating the entire real DOM
directly, React:
2. Component-Based Architecture
React follows a component-based approach, where the UI is broken down into reusable
components. These components:
React usesJSX, a syntax extension that allows developers to write HTML inside JavaScript.
JSX makes the code:
React uses one-way data binding, meaning data flows in a single direction from parent
components to child components via props. This provides better control over data and helps
maintain predictable behavior.
Module-5 Back-End Integration and Deployment:
5. React Router
React provides a React Router for managing navigation in single-page applications (SPAs). It
enables dynamic routing without requiring full-page reloads.
What is Babel?
Babel is a JavaScript compiler that can translate markup or programming languages into
JavaScript.
Babel is available for different conversions. React uses Babel to convert JSX into JavaScript.
Applications of React
React vs Angular
Module-5 Back-End Integration and Deployment:
React Angular
React uses one-way data binding, Angular uses two-way data binding
React uses JSX (JavaScript XML) for Angular uses HTML templates with
templating. special Angular directives.
React uses the Virtual Dom concept Angular used the Real Dom concept
History of React
● React is now a widely used framework for building modern web and mobile
apps, supported by a strong community and major companies.
React JS ReactDOM
ReactDom is a core react package that provides methods to interact with the Document
Object Model or DOM. This package allows developers to access and modify the DOM.
How to use ReactDOM ?
To use the ReactDOM in any React web app we must first install the react-dom package in
our project. To install the react-dom package use the following command.
// Installing
npm i react-dom
After installing the package use the following command to import the package in your
application file
// Importing
import ReactDOM from 'react-dom'
After installing react-dom it will appear in the dependenices in [Link] file like:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
}
React Render HTML
React renders HTML to the web page by using a function called createRoot() and its method
render().
The purpose of the function is to define the HTML element where a React component should
be displayed.
The render() method is then called to define the React component that should be rendered.
There is another folder in the root directory of your React project, named "public". In this
folder, there is an [Link] file.
You'll notice a single <div> in the body of this file. This is where our React application will
be rendered.
React Components
Components are independent and reusable bits of code. They serve the same purpose as
JavaScript functions, but work in isolation and return HTML.
Components come in two types, Class components and Function components, in this tutorial
we will concentrate on Function components
Create Your First Component
When creating a React component, the component's name MUST start with an upper
case letter.
Class Component
The component also requires a render() method, this method returns HTML.
Function Component
Here is the same example as above, but created using a Function component instead.
Module-5 Back-End Integration and Deployment:
A Function component also returns HTML, and behaves much the same way as a Class
component, but Function components can be written using much less code, are easier to
understand, and will be preferred in this tutorial.
function Car() {
return <h2>Hi, I am a Car!</h2>;
}
Rendering a Component
Now your React application has a component called Car, which returns an <h2>
element.
To use this component in your application, use similar syntax as normal HTML: <Car
/>
Example
[Link](<Car />);
Vue Introduction
Vue is a JavaScript Framework
Similar frameworks to Vue are React and Angular, but Vue is more lightweight and easier to
start with.
Vue is distributed as a JavaScript file, and can be added to a web page with a script tag:
<script
src="[Link]
</script>
If some of these points are hard to understand, don't worry, you will understand at the end of
the tutorial.
There are two different ways to write code in Vue: The Options API and The Composition
API.
The underlying concepts are the same for both the Options API and Composition API, so
after learning one, you can easily switch to the other.
The Options API is what is written in this tutorial because it is considered to be more
beginner-friendly, with a more recognizable structure.
Take a look at this page at the end of this tutorial to learn more about the differences between
the Options API and the Composition API.
Module-5 Back-End Integration and Deployment:
My first page
We will now learn how we can create our very first Vue web page, in 5 basic steps:
These steps are described in detail below, with the full code in a 'Try It Yourself' example in
the end.
<!DOCTYPE html>
<html lang="en">
<head>
<title>My first Vue page</title>
</head>
<body>
</body>
</html>
Put a <div> tag inside the <body> tag and give it an id:
<body>
<div id="app"></div>
</body>
To help our browser to interpret our Vue code, add this <script> tag:
Module-5 Back-End Integration and Deployment:
<script src="[Link]
This is called the Vue instance and can contain data and methods and other things, but now it
just contains a message.
On the last line in this <script> tag our Vue instance is connected to the <div id="app"> tag:
<div id="app"></div>
<script src="[Link]
<script>
[Link]('#app')
</script>
Finally, we can use text interpolation, a Vue syntax with double curly braces {{ }} as a
placeholder for data.
The browser will exchange {{ message }} with the text stored in the 'message' property
inside the Vue instance.
Text Interpolation
Text interpolation is when text is taken from the Vue instance to show on the web page.
Then the browser finds the text inside the 'message' property of the Vue instance and
translates the Vue code into this:
Simple JavaScript expressions can also be written inside the double curly braces {{ }}.
PHP(Hypertext Preprocessor)
PHP is a popular, open-source scripting language mainly used in web development. It runs on
the server side and generates dynamic content that is displayed on a web application. PHP is
easy to embed in HTML, and it allows developers to create interactive web pages and handle
tasks like database management, form handling, and user authentication.
● PHP code is executed on the server, generating HTML output sent to the client's
browser.
● It is a dynamically typed language, allowing variables to change types during
execution, offering flexibility in coding.
● PHP is platform-independent, which means it can run on various operating
systems such as Windows, Linux, and macOS.
● PHP supports session management, which allows tracking user activities across
different pages on a website.
Module-5 Back-End Integration and Deployment:
PHP Versions
PHP has been a key technology in web development from the beginning, helping create
interactive websites and web applications. Over the years, PHP has evolved, introducing new
features, performance improvements, and better security. Understanding the different PHP
versions and their changes is essential for developers to keep their code up to date and take
advantage of the latest improvements.
Here we explore the evolution of PHP from PHP 3 to the latest stable PHP 8.4 and offers
practical guidance for choosing and migrating between versions.
Let’s take a look at the different versions of PHP, their release years, and the key features
they introduced:
What is a PHP File?
● PHP files can contain text, HTML, CSS, JavaScript, and PHP code
Module-5 Back-End Integration and Deployment:
● PHP code is executed on the server, and the result is returned to the browser as plain
HTML
● PHP files have extension ".php"
With PHP you are not limited to output HTML. You can output images or PDF files. You can
also output any text, such as XHTML and XML.
Why PHP?
PHP Syntax
Basic PHP Syntax
PHP code is executed between PHP tags, allowing the integration of PHP code within
HTML. The most common PHP tag is <?php ... ?>, which is used to enclose PHP code. The
<?php ....?> is called Escaping to PHP.
<?php
// code
?>
The script starts with <?php and ends with ?>. These tags are also called 'Canonical PHP
tags'. Everything outside of a pair of opening and closing tags is ignored by the PHP parser.
The open and closing tags are called delimiters. Every PHP command ends with a semi-colon
(;).
Basic Example of PHP
<?php
Module-5 Back-End Integration and Deployment:
echo and print are more or less the same. They are both used to output data to the screen.
The differences are small: echo has no return value while print has a return value of 1 so it
can be used in expressions. echo can take multiple parameters (although such usage is rare)
while print can take one argument. echo is marginally faster than print.
echo "Hello";
//same as:
echo("Hello");
The print statement can be used with or without parentheses: print or print().
print "Hello";
//same as:
print("Hello");
Example:
<?php
?>
○ Download XAMPP:
Go to [Link]
Download the installer for Windows.
○ Install XAMPP:
Run the installer and follow the steps.
During installation, make sure Apache and PHP are selected.
phpinfo();
?>
Comments in PHP
Comments are used to make code more readable by explaining the purpose of specific
code blocks. Comments are ignored by the PHP interpreter.
As the name suggests, these are single line or short relevant explanations that one can
add to their code. To add this, we need to begin the line with (//) or (#).
<?php
// This is a single line comment
// These cannot be extended to more lines
echo "Hello World!";
# This is also a single line comment
?>
It is used to accommodate multiple lines with a single tag and can be extended to
many lines as required by the user. To add this, we need to begin and end the line with
(/*...*/)
<?php
/* This is a multi line comment
In PHP variables are written
by adding a $ sign at the
beginning.*/
Module-5 Back-End Integration and Deployment:
PHP Variables
A variable in PHP is a container used to store data such as numbers, strings, arrays, or
objects. The value stored in a variable can be changed or updated during the execution of the
script.
To declare a variable in PHP, you simply assign a value to it using the $ symbol followed by
the variable name. PHP variables are case-sensitive and must start with a letter or an
underscore, followed by any number of letters, numbers, or underscores.
Syntax:
$variable_name = value;
<?php
$name = "XYZ"; // String
$age = 30; // Integer
$salary = 45000.50; // Float
$isEmployed = true; // Boolean
?>
In PHP, it’s important to follow certain naming conventions for PHP variables to ensure
readability and maintainability:
Module-5 Back-End Integration and Deployment:
● Start with a Letter or Underscore: Variable names must begin with a letter or an
underscore (_), not a number.
● Use Descriptive Names: Variable names should be descriptive of their purpose,
e.g., $userName, $totalAmount.
● Case Sensitivity: PHP variable names are case-sensitive, meaning $name and
$Name are different variables.
● Avoid Reserved Words: Do not use PHP reserved words or keywords as variable
names (e.g., function, class, echo).
<?php
The scope of a variable refers to where it can be accessed within the code. PHP variables can
have local, global, static, or superglobal scope.
Variables declared within a function have local scope and cannot be accessed outside the
function. Any declaration of a variable outside the function with the same name (as within the
function) is a completely different variable.
The variables declared outside a function are called global variables. These variables can be
accessed directly outside a function. To get access within a function we need to use the
“global” keyword before the variable to refer to the global variable.
Python
Module-5 Back-End Integration and Deployment:
Python was created by Guido van Rossum in 1991 and further developed by the Python
Software [Link] is one of the most popular programming languages. It’s simple
to use, packed with features and supported by a wide range of libraries and frameworks. Its
clean syntax makes it beginner-friendly.
● A high-level language, used in web development, data science, automation, AI
and more.
● Known for its readability, which means code is easier to write, understand and
maintain.
● Backed by library support, so we don’t have to build everything from scratch,
there’s probably a library that already does what we need.
Why Python?
● Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
● Python has a simple syntax similar to the English language.
● Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
● Python runs on an interpreter system, meaning that code can be executed as soon as it
is written. This means that prototyping can be very quick.
● Python can be treated in a procedural way, an object-oriented way or a functional way.
● Instagram: This popular social media app relies on Python’s simplicity for scaling
and handling millions of users.
● Spotify: Python is used for backend services and machine learning to personalize
music recommendations.
● Dropbox: The file hosting service uses Python for both its desktop client and
server-side operations.
● Netflix: Python powers key components of Netflix’s recommendation engine and
content delivery systems (CDN).
● Google: Python is one of the key languages used in Google for web crawling,
testing and data analysis.
● Uber: Python helps Uber handle dynamic pricing and route optimization using
machine learning.
● Pinterest: Python is used to process and store huge amounts of image data
efficiently.
Understanding input and output operations is fundamental to Python programming. With the
print() function, we can display output in various formats, while the input() function enables
interaction with users by gathering input during program execution.
Python's input() function is used to take user input. By default, it returns the user input in
form of a string.
Example:
In this example, "Hello, World!" is a string literal enclosed within double quotes. When
executed, this statement will output the text to the console.
print("Hello, World!")
How does this work:
● print() is a built-in Python function that tells the computer to show something on
the screen.
● The message "Hello, World!" is a string, which means it's just text. In Python,
strings are always written inside quotes (either single ' or double ").
● Anything after # in a line is a comment. Python ignores comments when running
the code, but they help people understand what the code is doing.
● Comments are helpful for explaining code, making notes or skipping lines while
testing.
"""
This is a multi-line comment.
It can be used to describe larger sections of code.
"""
Python Variables
In Python, variables are used to store data that can be referenced and manipulated during
program execution. A variable is essentially a name that is assigned to a value. Unlike many
other programming languages, Python variables do not require explicit declaration of type.
The type of the variable is inferred based on the value assigned.
Variables act as placeholders for data. They allow us to store and reuse values in our program.
Example:
Python Operators
In Python programming, operators in general are used to perform operations on values and
variables. These are standard symbols used for logical and arithmetic operations. In this
article, we will look into different types of Python operators.
x = 20 int
x = 20.5 float
x = 1j complex
x = range(6) range
What is [Link]?
[Link] is a free, open-source JavaScript runtime that runs on Windows, Mac, Linux, and
more.
Module-5 Back-End Integration and Deployment:
It lets you execute JavaScript code outside of a web browser, enabling server-side
development with JavaScript
Why [Link]?
[Link] excels at handling many simultaneous connections with minimal overhead, making it
perfect for:
Its non-blocking, event-driven architecture makes it highly efficient for I/O-heavy workloads.
Asynchronous Programming
This means it can keep working while waiting for tasks like reading files or talking to a
database.
With asynchronous code, [Link] can handle many things at once—making it fast and
efficient.
1. Go to [Link]
2. Download the LTS (Long Term Support) version
3. Run the installer and follow the instructions
Verify Installation
Module-5 Back-End Integration and Deployment:
node --version
npm --version
You should see version numbers for both [Link] and npm (Node Package Manager).
Troubleshooting
Getting Started
Once you have installed [Link], let's create your first server that says "Hello World!" in a
web browser.
[Link]
When someone visits your computer on port 8080, it will show "Hello World!".
Explanation:
Module-5 Back-End Integration and Deployment:
Line Description
[Link]((req, res) => { ... }) This creates a server that handles incoming
requests (req) and sends responses (res).
[Link](200, {'Content-Type': Sets the HTTP status code to 200 (OK) and
'text/plain'}); the content type to plain text.
[Link]('Hello, this is your first [Link] Ends the response and sends the text back
web server!'); to the browser.
[Link] files must be initiated in the "Command Line Interface" program of your computer.
How to open the command line interface on your computer depends on the operating system.
For Windows users, press the start button and look for "Command Prompt", or simply write
"cmd" in the search field.
Navigate to the folder that contains the file "[Link]", the command line interface window
should look something like this:
C:\Users\Your Name>_
The file you have just created must be initiated by [Link] before any action can take place.
Start your command line interface, write node [Link] and hit enter:
Module-5 Back-End Integration and Deployment:
Initiate "[Link]":
If anyone tries to access your computer on port 8080, they will get a "Hello World!" message
in return!
RESTful APIs provide a flexible, lightweight way to integrate applications and enable
communication between different systems.
RESTful APIs use HTTP requests to perform CRUD operations (Create, Read, Update,
Delete) on resources, which are represented as URLs.
REST is stateless, meaning each request from a client to a server must contain all the
information needed to understand and process the request.
Always use the most specific method that matches your operation's intent.
Module-5 Back-End Integration and Deployment:
A well-designed API follows consistent patterns that make it intuitive and easy to use. Good
API design is crucial for developer experience and long-term maintainability.
Design Considerations:
● Resource Naming: Use nouns, not verbs (e.g., /users not /getUsers)
● Pluralization: Use plural for collections (/users/123 not /user/123)
● Hierarchy: Nest resources to show relationships (/users/123/orders)
● Filtering/Sorting: Use query parameters for optional operations
● Versioning Strategy: Plan for API versioning from the start (e.g., /v1/users vs
/v2/users).
[Link] with [Link] provides an excellent foundation for building RESTful APIs.
The following sections outline best practices and patterns for implementation.
Key Components:
[Link] is the most popular framework for building REST APIs in [Link].
// routes/[Link]
// [Link]
[Link]([Link]());
[Link]('/api/users', userRoutes);
[Link](8080, () => {
[Link]('Server is running on port 8080');
});
Database Integration
Module-5 Back-End Integration and Deployment:
A full-stack web developer is a person who can develop both client and server software.
In addition to mastering HTML and CSS, he/she also knows how to:
Build a Full-Stack CRUD App Using React, Node, MySQL for Beginners
Advantages
Disadvantages
Let's build a simple full-stack web application step by step. We'll use:
● Add a task
● Delete task
● Store tasks in a MongoDB database
task-tracker/
├── backend/
│ ├── [Link]
│ ├── models/
│ │ └── [Link]
│ └── routes/
│ └── [Link]
├── frontend/
│ ├── public/
│ │ └── [Link]
│ └── src/
│ ├── [Link]
│ ├── [Link]
│ └── components/
│ └── [Link]
└── [Link]
Module-5 Back-End Integration and Deployment:
});
// Toggle completion
[Link]('/:id', async (req, res) => {
Module-5 Back-End Integration and Deployment:
// Delete a task
[Link]('/:id', async (req, res) => {
await [Link]([Link]);
[Link](204).end();
});
[Link] = router;
[Link](cors());
[Link]([Link]());
[Link]('/api/tasks', tasksRoute);
[Link]('mongodb://localhost:27017/taskdb')
cd frontend
setTasks([Link]);
};
useEffect(() => {
fetchTasks();
}, []);
Module-5 Back-End Integration and Deployment:
setTitle('');
fetchTasks();
};
await [Link](`${API_URL}/${id}`);
fetchTasks();
};
await [Link](`${API_URL}/${id}`);
fetchTasks();
};
return (
<div>
<h2>Task Tracker</h2>
<input
value={title}
placeholder="New Task"
/>
Module-5 Back-End Integration and Deployment:
<button onClick={addTask}>Add</button>
<ul>
{[Link](task => (
<li key={task._id}>
<span
>
{[Link]}
</span>
</li>
))}
</ul>
</div>
);
// [Link]
return (
<div className="App">
<TaskList />
</div>
);
// [Link]
[Link]([Link]('root')).render(<App />);
cd backend
node [Link]
Start Frontend
cd frontend
npm start
What is CORS?
Project Overview
● Frontend: [Link]
● Backend: [Link] with [Link]
● Database: MongoDB
● Tools: Axios, CORS, Mongoose
Objectives
System Architecture
Implementation Details
Frontend (React)
Backend (Express)
Database (MongoDB)
Key Features
1. CORS Issues
2. MongoDB Connectivity
3. State Sync
Outcome
Future Enhancements
Conclusion
Module-5 Back-End Integration and Deployment:
This case study demonstrates a complete, modular full-stack application build. It highlights
common issues and best practices for beginners and intermediate developers building web
apps using the MERN (MongoDB, Express, React, [Link]) stack.
Cloud platforms provide ready-to-use infrastructure and services for deploying [Link]
applications with minimal configuration. These platforms abstract away much of the
complexity of infrastructure management.
1. Heroku
🔹 Overview:
Heroku is a cloud platform that allows developers to deploy, manage, and scale applications
quickly. It supports multiple programming languages and offers an easy deployment method
using Git.
🔹 Key Features:
● Simple deployment via Git
● Auto-scaling
🔹 Best Use:
Module-5 Back-End Integration and Deployment:
● Quick prototyping
🔹 Step-by-Step Deployment:
✅ Prerequisites:
● Install Heroku CLI
● Install Git
✅ Steps:
Login to Heroku CLI:
heroku login
cd myapp
npm init -y
Create [Link]:
const express = require('express');
});
[Link](PORT, () => {
});
git add .
heroku create
heroku open
🔹 Key Features:
● Auto-scaling and load balancing
Module-5 Back-End Integration and Deployment:
● Health monitoring
🔹 Best Use:
● Scalable, production-grade enterprise applications
🔹 Step-by-Step Deployment:
✅ Prerequisites:
● AWS account
● Install EB CLI
● [Link] app
✅ Steps:
[Link] your project:
eb init
○ Choose region
🔹 Key Features:
● Auto-scaling
🔹 Best Use:
● High-traffic apps
🔹 Step-by-Step Deployment:
✅ Prerequisites:
● Install Google Cloud SDK
✅ Steps:
1. Login and initialize SDK:
gcloud auth login
gcloud init
Module-5 Back-End Integration and Deployment:
2. Create [Link]:
This configures App Engine for your [Link] app.
runtime: nodejs18
instance_class: F1
Handlers:
- url: /.*
script: auto
[Link] applications are vulnerable to a wide range of attacks if not secured properly.
Hackers can:
Securing your application is not optional, it’s mandatory to protect your users and your
server.
Problem:
If the application crashes, error messages may reveal sensitive information like:
Module-5 Back-End Integration and Deployment:
● File paths
● Database structure
● Server configuration
Best Practice:
● Use:
Best Practice:
○ express-validator
○ [Link]
🔸 3. Use HTTPS
Problem:
Best Practice:
const options = {
key: [Link]('[Link]'),
cert: [Link]('[Link]')
};
[Link](options, app).listen(443);
Attackers inject malicious code into your app (e.g., SQL queries).
Best Practice:
● Use parameterized queries for SQL (with packages like mysql2, pg)
Example:
Best Practice:
● X-Content-Type-Options
● Content-Security-Policy
● X-Frame-Options
Best Practice:
Module-5 Back-End Integration and Deployment:
Best Practice:
[Link](limiter);
Best Practice:
● Use:
npm outdated
npm update
Best Practice:
require('dotenv').config();
const dbPassword = [Link].DB_PASSWORD;
.env:
DB_PASSWORD=your_secret_password
🔸 1. What is Authentication?
➤ Definition:
➤ Goal:
✅ Examples of Authentication:
● Logging into a website with a username and password.
Method Description
const token = [Link]({ id: [Link], role: [Link] }, 'secretKey', { expiresIn: '1h' });
[Link]({ token });
});
🔸 2. What is Authorization?
➤ Definition:
➤ Goal:
✅ Examples of Authorization:
● An admin can create or delete users, but a regular user cannot.
● A user can view their own data, but not another user’s data.
Role-Based Access Control (RBAC) Access based on user roles (admin, editor,
viewer)
function authorizeRoles(...roles) {
return (req, res, next) => {
if () {
return [Link](403).send('Access denied');
}
next();
};
}
2. Use in Routes:
Definition Verifies who the user is Verifies what the user can access
How:
Benefits:
How:
Do:
// BAD (Blocking)
const data = [Link]('[Link]');
// GOOD (Non-blocking)
[Link]('[Link]', (err, data) => {
if (err) throw err;
[Link]([Link]());
});
Tips:
● Use indexes
Module-5 Back-End Integration and Deployment:
● Use pagination
-- BAD
-- GOOD
SELECT * FROM orders LIMIT 20 OFFSET 0;
Tools:
● Cloud load balancers like AWS ELB, Google Cloud Load Balancing
Best Practices:
● Use proper data structures (e.g., Map instead of Object for lookups)
Tools:
Module-5 Back-End Integration and Deployment:
9. Use HTTP/2
How:
Enable it on your web server (Nginx/Apache) or use a cloud provider that supports HTTP/2.
How:
Used mostly in frontend frameworks (React, Angular) and with images.