0% found this document useful (0 votes)
2 views

Part 06 - Server-Side Development

The document provides an overview of advanced web programming, focusing on server-side development with Node.js and Express.js. It covers key concepts such as Node.js's event-driven architecture, npm for package management, and Express.js for building web applications and APIs, including MySQL integration and authentication strategies. Additionally, it discusses RESTful API design principles and best practices for secure authentication and authorization.

Uploaded by

3sfr3sfr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Part 06 - Server-Side Development

The document provides an overview of advanced web programming, focusing on server-side development with Node.js and Express.js. It covers key concepts such as Node.js's event-driven architecture, npm for package management, and Express.js for building web applications and APIs, including MySQL integration and authentication strategies. Additionally, it discusses RESTful API design principles and best practices for secure authentication and authorization.

Uploaded by

3sfr3sfr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Advanced Web Programming

Part 06 - Server-Side Development


Dr. Amjad AbuHassan

12/26/2024 Dr. Amjad AbuHassan 1


Node.js and Express.js

12/26/2024 Dr. Amjad AbuHassan 41


Node.js and npm

12/26/2024 Dr. Amjad AbuHassan 42


What is Node.js?
● Definition:
● Node.js is a JavaScript runtime built on Chrome's V8 engine.
● It enables JavaScript to be executed outside of the web browser.
● Core Features:
● Event-driven, non-blocking I/O model.
● Single-threaded but capable of handling many concurrent connections.
● High performance due to V8 engine’s efficient execution.
● Built-in modules for file system access, networking, and more.
● Use Cases: RESTful, real-time apps, command-line tools, microservices, and more.
12/26/2024 Dr. Amjad AbuHassan 43
The Event-Driven Architecture of Node.js
● Event Loop:
● The core of Node.js's non-blocking I/O.

● Continuously monitors the call stack and handles


events.

● Event Emitter:
● Allows objects to emit named events.

● Listeners are registered to handle these events


asynchronously.

12/26/2024 Dr. Amjad AbuHassan 44


Understanding npm (Node Package Manager)
● What is npm? ● Script automation: Simplifies the
● The default package manager for Node.js. automation of repetitive tasks.
● Provides access to a vast repository of ● Common Commands:
packages via the npm registry. ● npm init: Initializes a new project with a
● Key Features: package.json file.

● Dependency management: Automatically ● npm install <package>: Installs a


installs and manages packages. package and adds it to dependencies.

● Version control: Ensures consistent ● npm run <script>: Runs a script


versions of packages across environments. defined in package.json.

12/26/2024 Dr. Amjad AbuHassan 48


Exploring the package.json File
● Key Sections:
● Name and Version: Defines the project’s
name and version.

● Scripts: Defines custom scripts for tasks like


testing, building, and starting the application.

● Dependencies: Lists packages required to run


the application.

● DevDependencies: Lists packages required


only for development.
12/26/2024 Dr. Amjad AbuHassan 49
Managing Dependencies with npm
● Installing Dependencies:
● npm install <package> - Installs a package and adds it to dependencies.

● npm install <package> --save-dev - Installs a package and adds it to


devDependencies.

● Updating Dependencies:
● npm update - Updates all packages to the latest versions specified by the semver range in
package.json.

● npm outdated - Lists outdated packages that need updating.

12/26/2024 Dr. Amjad AbuHassan 50


Managing Dependencies with npm cont.
● Removing Dependencies:
● npm uninstall <package> - Removes a package from node_modules and
package.json.

● Versioning:
● Semantic Versioning (semver): MAJOR.MINOR.PATCH (e.g., ^1.2.3).

● Caret ^: Updates to the latest minor/patch version.

● Tilde ~: Updates to the latest patch version only.

12/26/2024 Dr. Amjad AbuHassan 51


npm Scripts and Automation
● What are npm Scripts?
● Custom commands defined in package.json.

● Automate tasks like testing, building, and deployment.

● Common Scripts:
● "start": "node app.js" - Starts the application.

● "test": "mocha" - Runs tests using Mocha.

● "build": "webpack --config webpack.config.js" - Builds the project using


Webpack.

12/26/2024 Dr. Amjad AbuHassan 52


npm Scripts and Automation cont.
● Running npm Scripts:
● Command: npm run <script-name>

● Example: npm run start

● Predefined Scripts:
● prestart, poststart, pretest, posttest - Automatically run before or after a
specific script.

12/26/2024 Dr. Amjad AbuHassan 53


Working with Node.js Modules
Creating a Module
● What are Modules?
● Reusable pieces of code that can be
exported and imported.

● Encourage modularity and code reuse.

● Built-in Modules: Examples: fs (File


System), http, path, os. Using a Module

12/26/2024 Dr. Amjad AbuHassan 54


Node.js Ecosystem and Community
● npm Registry:
● Over 1.5 million packages available for use.

● Libraries for virtually any functionality you need.

● Popular Libraries:
● Lodash: A utility library for working with arrays, objects, and functions.

● Moment.js: A library for parsing, validating, manipulating, and formatting dates.

● Axios: A promise-based HTTP client for making requests.

12/26/2024 Dr. Amjad AbuHassan 59


Express.js

12/26/2024 Dr. Amjad AbuHassan 61


Introduction to Express.js
● What is Express.js?
● A fast, unopinionated, and minimalist web framework for Node.js.
● Provides essential features for building web applications and APIs.
● Core Features:
● Simplified routing for handling HTTP requests.
● Middleware support for handling tasks like authentication, logging, and error handling.
● Integration with various templating engines.
● Flexibility in structuring your application.
● Use Cases: RESTful APIs, single-page applications (SPAs), microservices.
12/26/2024 Dr. Amjad AbuHassan 62
Introduction to MySQL
● What is MySQL?
● MySQL is an open-source relational database management system (RDBMS).
● It uses structured query language (SQL) to manage and manipulate data.
● Key Features:
● Reliable and widely adopted in the industry.
● Supports complex queries, transactions, and data integrity.
● Scalability to handle large datasets.
● Multi-user access with strong security features.
● Use Cases: E-commerce platforms, CMS, financial applications, and more.
12/26/2024 Dr. Amjad AbuHassan 63
Setting Up an Express.js Project
my-express-app/
├── node_modules/
● Step 1: Initialize the Project ├── package.json
● Command: npm init -y ├── app.js
├── config/
● Generates a package.json file to manage dependencies.
│ └── db.js
● Step 2: Install Dependencies ├── routes/
│ └── index.js
● npm install express mysql
├── controllers/
● Installs Express.js and the MySQL client library. │ └── taskController.js

● Step 3: Create the Project Structure ├── models/


│ └── taskModel.js
● Example Structure: └── public/

12/26/2024 Dr. Amjad AbuHassan 64


Configuring MySQL Connection in Express.js
● Step 1: Create a Database
Configuration File
● File: config/db.js

12/26/2024 Dr. Amjad AbuHassan 65


Configuring MySQL Connection in Express.js
cont.
● Step 2: Import and Use
the Database
Connection
● Code Example in app.js:

12/26/2024 Dr. Amjad AbuHassan 66


Defining Models in Express.js
● What is a Model?
● A model represents a table in
the database and provides an
interface for interacting with
it.

● Creating a Model for Tasks


● File: models/taskModel.js

12/26/2024 Dr. Amjad AbuHassan 67


Creating Routes in Express.js
● What is a Route?
● A route defines an
endpoint in the application
that responds to HTTP
requests.

● Setting Up Routes
● File: routes/index.js

12/26/2024 Dr. Amjad AbuHassan 68


Creating Routes in Express.js cont.
● Using Routes in app.js:

12/26/2024 Dr. Amjad AbuHassan 69


Implementing Controllers in Express.js
● What is a Controller?
● A controller handles the
logic for processing
requests and interacting
with models.

● Creating a Task Controller


● File:
controllers/taskController.js

12/26/2024 Dr. Amjad AbuHassan 70


Performing CRUD Operations with MySQL
● Create a New Task (POST Request)

12/26/2024 Dr. Amjad AbuHassan 71


Performing CRUD Operations with MySQL
cont.
● Read All Tasks (GET Request)

12/26/2024 Dr. Amjad AbuHassan 72


Performing CRUD Operations with MySQL
cont.
● Update a Task (PUT Request)

12/26/2024 Dr. Amjad AbuHassan 73


Performing CRUD Operations with MySQL
cont.
● Delete a Task (DELETE Request)

12/26/2024 Dr. Amjad AbuHassan 74


Middleware in Express.js
● What is Middleware?
● Middleware functions execute during the request-response cycle.

● Can modify the request and response objects, end the request-response cycle, or call the next
middleware.

● Common Middleware Examples:


● Body Parsing: Parse JSON and URL-encoded data

● Logging: Log details of incoming requests.

● Error Handling: Catch and handle errors in the application.

12/26/2024 Dr. Amjad AbuHassan 75


Middleware in Express.js cont.

12/26/2024 Dr. Amjad AbuHassan 76


Best Practices for Express.js and MySQL
Integration
DB_HOST=localhost
● Secure Database Connections:
DB_USER=root
● Use environment variables for sensitive DB_PASS=yourpassword
information like database credentials. DB_NAME=yourdatabase

● Example: .env

● Load environment variables using dotenv:

12/26/2024 Dr. Amjad AbuHassan 77


Best Practices for Express.js and MySQL
Integration cont.
● Handle SQL Injection:
● Always use parameterized queries to
prevent SQL injection attacks.

● Optimize Database Queries:


● Index important columns to improve
query performance.

● Avoid SELECT * in large tables; select


only the columns you need.

12/26/2024 Dr. Amjad AbuHassan 78


Authentication and Authorization
Strategies

12/26/2024 Dr. Amjad AbuHassan 79


Introduction to Authentication and
Authorization
● Authentication:
● The process of verifying the identity of a user.
● Common methods: Passwords, biometrics, multi-factor authentication (MFA).
● Authorization:
● Determines what an authenticated user is allowed to do.
● Based on user roles, permissions, and policies.
● Key Differences:
● Authentication: "Who are you?"
● Authorization: "What can you do?"
12/26/2024 Dr. Amjad AbuHassan 80
Basic Authentication Strategies
● Username and Password:
● The most common form of authentication.

● User submits credentials, which are checked against stored records.

12/26/2024 Dr. Amjad AbuHassan 81


Basic Authentication Strategies cont.
● Multi-Factor Authentication (MFA):
● Adds an additional layer of security beyond just passwords.

● Examples: SMS codes, email verification, authenticator apps.

12/26/2024 Dr. Amjad AbuHassan 82


Token-Based Authentication
● What is Token-Based Authentication? ● Example: JWT Structure
● Users receive a token upon successful ● Header: Algorithm and token type.
login. ● Payload: User information and claims.
● Token is sent with each request to ● Signature: Verifies the token’s integrity.
authenticate the user.
● JSON Web Tokens (JWT):
● A popular token format that is stateless
and portable.
● Contains encoded JSON data, including
claims and signature.

12/26/2024 Dr. Amjad AbuHassan 83


Implementing Middleware for Authentication
and Authorization
● What is Middleware?
● Functions that execute during
the request-response cycle.

● Can be used to enforce


authentication and authorization
checks.

● Authentication Middleware
Example:

12/26/2024 Dr. Amjad AbuHassan 90


Implementing Middleware for Authentication
and Authorization cont.
● Authorization Middleware Example:

12/26/2024 Dr. Amjad AbuHassan 91


Best Practices for Secure Authentication and
Authorization
● Use HTTPS:
● Always use HTTPS to encrypt data in transit.

● Protects sensitive information such as


tokens and credentials.

● Implement Rate Limiting:


● Prevent brute-force attacks by limiting the
number of login attempts.

● Example: Use express-rate-limit


middleware
12/26/2024 Dr. Amjad AbuHassan 94
API Styles

12/26/2024 Dr. Amjad AbuHassan 98


REST: Representational State
Transfer

12/26/2024 Dr. Amjad AbuHassan 99


What is REST?
● Definition: REST is an architectural style for designing networked applications.
● Origin: Introduced by Roy Fielding in his 2000 doctoral dissertation.
● Purpose: Provides a standardized way for systems to communicate over HTTP.
● Core Concept: RESTful services expose resources (data entities) through a set of
well-defined, stateless operations.

12/26/2024 Dr. Amjad AbuHassan 100


Core Principles of REST
● Statelessness: Each request from the client to the server must contain all the
information needed to understand and process the request.
● Client-Server Architecture: Separation of concerns, where the client and server
operate independently.
● Uniform Interface: Standardized API structure with predictable URLs and HTTP
methods.
● Resource-Based: Everything in REST is considered a resource, identified by a
unique URL.
12/26/2024 Dr. Amjad AbuHassan 101
Core Principles of REST cont.
● Representation: Resources can have different representations (e.g., JSON, XML)
that are transferred between client and server.
● Stateless Communication: No client context is stored on the server between
requests.
● Cacheable: Responses can be cached to improve performance.

12/26/2024 Dr. Amjad AbuHassan 102


RESTful HTTP Methods
● GET: Retrieve a resource or a list of resources.
● POST: Create a new resource.
● PUT: Update an existing resource.
● DELETE: Remove a resource.
● PATCH: Partially update a resource.
● HEAD: Retrieve metadata of a resource without the body.
● OPTIONS: Describe the communication options for the target resource.

12/26/2024 Dr. Amjad AbuHassan 103


Resource Identification in REST
● Resource: Any piece of data that can be named, such as a document, image, or
service.
● URI (Uniform Resource Identifier): The unique identifier for each resource.
● Best Practices:
● Use nouns, not verbs (e.g., /users not /getUsers).

● Organize resources hierarchically (e.g., /users/{userId}/orders).

● Keep URIs simple and intuitive.

● Use plural nouns for collections (e.g., /books for a collection of book resources).

12/26/2024 Dr. Amjad AbuHassan 104


RESTful API Design Patterns
● Resource Collections:
● Represent a collection of resources (e.g., /users).

● Use GET to retrieve the collection, POST to add to it.

● Sub-Resources:
● Represent resources that belong to a parent resource (e.g., /users/{userId}/orders).

● Reflect hierarchical relationships.

12/26/2024 Dr. Amjad AbuHassan 105


RESTful API Design Patterns cont.
● Action Endpoints:
● Avoid actions in URIs, but if necessary, use sub-resource or query parameters (e.g.,
/users/{userId}/activate or /users/{userId}?action=activate).

● Filtering and Pagination:


● Use query parameters to filter results (e.g., /users?active=true).

● Implement pagination for large collections (e.g., /users?page=2&limit=10).

12/26/2024 Dr. Amjad AbuHassan 106


Error Handling in RESTful APIs
● HTTP Status Codes:
● 200 OK: Request succeeded.

● 400 Bad Request: Client error due to invalid input.

● 401 Unauthorized: Authentication is required and has failed.

● 403 Forbidden: Client authenticated but does not have permission.

● 404 Not Found: Requested resource could not be found.

● 500 Internal Server Error: Server encountered an unexpected condition.

12/26/2024 Dr. Amjad AbuHassan 109


Error Handling in RESTful APIs cont.
● Error Response Structure:
● Include a clear error message and a unique error code.

● Provide details on what went wrong and how to correct it.

12/26/2024 Dr. Amjad AbuHassan 110


RESTful API Authentication Methods
● Basic Authentication:
● Simple method using base64-encoded credentials in the HTTP header.

● Example header: Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=.

● Not secure without HTTPS.

● Token-Based Authentication:
● JWT (JSON Web Tokens): Tokens are signed and can be verified by the server without needing
to store session information.

● OAuth 2.0: Widely used for third-party authentication, involves exchanging tokens between
client and server.
12/26/2024 Dr. Amjad AbuHassan 111
GraphQL: A Query Language for
APIs

12/26/2024 Dr. Amjad AbuHassan 130


Introduction to GraphQL
● Definition: a query language for APIs and a runtime for executing those queries.
● History: Developed by Facebook in 2012, released publicly in 2015.
● Key Advantages:
● Precise data fetching (no over-fetching or under-fetching).

● Single, consistent API endpoint.

● Strongly-typed schema.

12/26/2024 Dr. Amjad AbuHassan 131


Key Reasons GraphQL Was Invented
● Client-driven Queries: GraphQL allows clients to specify exactly what data they
want in a single request.
● Reduce Over-fetching and Under-fetching: With REST, you might receive too much
data (over-fetching) or too little (under-fetching, requiring multiple endpoints to
get all needed data). GraphQL solves both by letting clients request precisely the
data they need.
● Single Endpoint: GraphQL commonly uses a single endpoint (often /graphql) and
the query defines what to fetch.
12/26/2024 Dr. Amjad AbuHassan 132
GraphQL vs. REST
● REST APIs: ● GraphQL APIs:
● Multiple endpoints. ● Usually a single endpoint.
● The server decides what data is ● The client specifies what data it needs
returned from each endpoint. (fields, relationships, nesting).
● Clients may have to make multiple ● Fetches multiple related resources in
requests to different endpoints to one go.
gather all required data.

12/26/2024 Dr. Amjad AbuHassan 133


GraphQL vs. REST cont.
● REST: To get a user and their posts: ● GraphQL: Make one query to /graphql:
{
1. GET /api/users/1 → returns user data
user(id: 1) {
2. GET /api/users/1/posts → returns user’s name

posts. email
posts {
title
content
}
}
}

12/26/2024 Dr. Amjad AbuHassan 134


Core Concepts of GraphQL
● Schema: The contract that defines the types, queries, mutations, and subscriptions
available in the API.
● Types: Define the shape and structure of the data (e.g., User, Post).
● Queries: Retrieve data from the server.
● Mutations: Modify data on the server (create, update, delete).
● Resolvers: Functions that process queries and mutations, returning the
appropriate data.
● Subscriptions: Real-time updates when data changes.
12/26/2024 Dr. Amjad AbuHassan 135
GraphQL Schema Structure
● Defining the Schema:
● Root Types: Query, Mutation, and Subscription.

● Fields: The data points available within each type.

● Arguments: Parameters that can be passed to fields

● Importance of Strong Typing: Ensures


data consistency and clear contracts.

12/26/2024 Dr. Amjad AbuHassan 136


Writing GraphQL Queries
● Query Syntax:
● Request specific fields.

● Use arguments to filter or refine data.

● Nested queries to fetch related data.

● Variables and Arguments: Passing dynamic data to queries.


● Advantages Over REST: No over-fetching or under-fetching.

12/26/2024 Dr. Amjad AbuHassan 137


Mutations in GraphQL
● Structure of Mutations:
● Similar to queries but intended for modifying data.

● Can include input types for complex data operations.

● Returning Data: Fetch the updated or newly created data immediately.


12/26/2024 Dr. Amjad AbuHassan 138
Understanding Resolvers
● What Are Resolvers?: Functions that
connect schema fields to data sources.
● Resolver Structure:
● Query Resolvers: Fetch and return data.

● Mutation Resolvers: Modify data and return


the result.

● Asynchronous Operations: Handling


async data fetching (e.g., from a DB).
12/26/2024 Dr. Amjad AbuHassan 139
Real-Time Applications:
Understanding WebSockets and
XMPP

12/26/2024 Dr. Amjad AbuHassan 155


Introduction to Real-Time Applications
● Definition: Real-time applications update information immediately after the data is
received.
● Importance: Critical in enhancing user experience.
● Examples:
● Chat applications (e.g., Slack, WhatsApp).

● Online multiplayer games.

● Live financial dashboards.

● Collaborative editing tools (e.g., Google Docs).

12/26/2024 Dr. Amjad AbuHassan 156


The Evolution of Real-Time Communication
on the Web
● Early techniques:
● Polling: Clients repeatedly ask the server for updates.

● Long Polling: Server holds the connection open until new information is available.

● Comet: A technique to push data to the client without a new request.

● Limitations: High latency, resource-intensive, not scalable.


● Introduction of WebSockets and XMPP: Revolutionized real-time web
communication.

12/26/2024 Dr. Amjad AbuHassan 157


WebSockets: An Overview
● Definition: A protocol providing full- ● Event-driven, allowing real-time data

duplex communication over a single exchange.

TCP connection. ● Common Use Cases:


● Key Features: ● Live chat applications.

● Persistent connection after the handshake. ● Stock price updates.

● Bi-directional communication. ● Multiplayer online games.

● Low latency.

12/26/2024 Dr. Amjad AbuHassan 158


How WebSockets Work
● WebSocket Handshake: receive messages anytime.

● Initiated via an HTTP request with a special ● WebSocket API Basics:


"Upgrade" header. ● WebSocket constructor.

● Server responds with a 101 status code, ● send(), onmessage, onopen, onclose
switching the protocol to WebSocket. events.

● Communication Flow:
● Persistent connection remains open.

● Both client and server can send and

12/26/2024 Dr. Amjad AbuHassan 159


Practical Example: Implementing WebSockets
Server Side Client Side

12/26/2024 Dr. Amjad AbuHassan 160

You might also like