UNIT IV Notes_removed - Converted
UNIT IV Notes_removed - Converted
• It is used to build web applications and APIs quickly and efficiently. It simplifies the • →used to configure settings in Express application.
process of building server-side web applications and APIs by providing robust tools and • →It allows the developer to control the behavior of various aspects of the app, such as view
features. Express is commonly used in full-stack JavaScript development because it rendering, request handling, and response formatting.
allows developers to manage routing, request handling, and middleware in a
streamlined way.
• Express is a part of the MEAN (MongoDB, Express.js, Angular, Node.js) and MERN
(MongoDB, Express.js, React, Node.js) stacks, which are popular JavaScript-based Common Settings:
full-stack development technologies.
• view engine: Specifies the template engine (e.g., Pug, EJS).
how Express fits in the full-stack environment: • case sensitive routing: When set to true, /Home and /home are treated as different routes.
1.Server-Side Framework: Express is used on the back-end . 2. Enable(setting)
• to set a specific setting to true.
It manages the routing (handling URLs and HTTP requests), middleware (handling processes • This function is used to enable a specific setting or configuration option within the
like authentication, validation, etc.), and communication between the client and the database. application. This method allows to control various behaviors of the Express server.
2.Handling Requests and Responses: to define how the application should respond to • It’s typically used for Boolean settings that either enable or disable a feature.
different HTTP requests (GET, POST, PUT, DELETE). • It can be thought of as equivalent to app.set(setting, true).
3.Middleware Support: to perform various tasks like parsing request bodies, managing
cookies, logging requests, etc.
4.RESTful APIs: Express is often used to create RESTful APIs, allowing the front-end (React, 3. Disable(setting)
Angular) to communicate with the back-end server.
• It is a shortcut to set a specific setting to false.
Getting Started with Express: • It disables a feature and can be seen as equivalent to app.set(setting, false).
Prerequisites:
Node.js: Express.js is built on Node.js, so need Node.js installed.
Basic JavaScript knowledge: Express.js uses JavaScript for server-side scripting.
Starting the Express server:
• Add the express module To begin implementing Express as the HTTP server for your Node.js application,
npm install express • need to create an instance and begin listening on a port.
var express = require('express’);
• Create an instance class to act as the http server for node.js application. var app = express();
1 2
app.listen(8080); res.send('Data submitted successfully!’);
• This tells the Express application to listen for incoming requests on port 8080. });
• The listen() method takes a port number as its argument, and here it is set to 8080. • app.get(): Defines a route handler for HTTP GET requests to the /about path.
When the server is running, it listens for HTTP requests on http://localhost:8080.
• '/about': This is the route or endpoint. When a user visits http://yourserver.com/about, this
function will handle the request.
var express = require('express'); • function (req, res): This is the callback function that is executed when the /about route is hit.
var https = require('https'); It takes two parameters:
var http = require('http');
var fs = require('fs'); • req (request): Represents the incoming HTTP request.
var app = express(); • res (response): Represents the outgoing HTTP response
var options = {
host: '127.0.0.1’, • res.send('This is the About page.'): Sends a response with the message "This is the About
key: fs.readFileSync('ssl/server.key’), page." back to the client.
cert: fs.readFileSync('ssl/server.crt')
}; • app.get() is used for handling HTTP GET requests, which are typically used for retrieving data
http.createServer (app).listen(80); from the server.
https.createServer (options, app).listen(443); • app.post() is used for handling HTTP POST requests, which are typically used for sending
app.get('/', function(req, res) { data to the server (such as form submissions).
res.send('Hello from Express');
}); • app.all() works the same as app.post() and app.get(). Here the call back function for app.all()
is called for every request for the specified path.
• host: '127.0.0.1': specifies that the server will be accessible only from the local machine app.all(‘*’,function(req,res){
(localhost).
// global handler for all paths
• key: fs.readFileSync('ssl/server.key'): reads the private key file (server.key) from the ssl/
directory. The key is required for establishing a secure HTTPS connection. });
• cert: fs.readFileSync('ssl/server.crt'): reads the certificate file (server.crt) from the ssl/
Applying parameters in routes:
directory. The certificate is also required for HTTPS and verifies the server's identity.
• Both the key and cert files are necessary for SSL/TLS communication, which ensures encrypted • several ways to pass parameters to routes, which can be useful for retrieving data, processing
and secure transmission between the server and clients. user input, and more.
• http.createServer(app).listen(80); creates an HTTP server using the http module and binds it
• Each method allows different types of data to be included in the request.
to port 80. Port 80 is the default port for HTTP (unsecured) traffic.
• The app instance (the Express application) handles incoming HTTP requests on port 80. 1. Query String Parameters
• https.createServer(options, app).listen(443);creates an HTTPS server using the https module
• This is commonly used for filtering, sorting, or sending small amounts of data.
and the options object containing the SSL/TLS certificate and key.
• It listens on port 443, which is the default port for HTTPS (secure) traffic. • Starts with: A ? symbol that marks the beginning of the query string in the URL.
• GET route on the root URL (/). When a client makes a GET request to http://localhost/ (or
• Key-value pairs: Parameters are expressed as key-value pairs separated by the = symbol.
https://localhost/), the server responds with the message "Hello from Express".
• Multiple parameters: Multiple key-value pairs are separated by &.
app.get('/find', function(req, res) {
II. CONGIGURING ROUTES
var url_parts= url.parse(req.url, true);
• Before the server can begin accepting requests, its need to define the routes.
3 5
var query = url_parts.query; res.send('User ID: ' + userId);
res.send('Finding Book: Author: ' + query.author +’Title: ‘+ query.title); });
}); • URL Request: /user/123
• Route Parameter: id
Example:
• Extracted Value: 123 → res.send() method returns Get user: 123
http://localhost:3000/find?author=John&title=AI
4. Applying callback function for defined parameters
Query Parameters:
When parsing the URL if Express finds a parameter that has a callback registered it
• author=John calls the parameter’s callback function before calling the route handler. More than one call back
function can be registered for a route.
• title=AI
app.param() method is used to register a callback function. It accepts the defined
Response: The server will respond with the text parameter as the first argument and then a callback function that receives the request , response ,
next and value parameter.
Finding Book: Author: John Title: AI
app.param(param,function(req,res,next,vakue){});
This route handler processes a URL with query parameters (?author=John&title=AI), parses
Example:
the query string to extract the parameters, and sends back a response that displays the values
of author and title. app.param('userid', function(req, res, next, value) {
'Page: ' + req.params[1]); The userid of 4983 is parsed from the URL and the consol.log() statement displays
example, consider the following URL: III. Using Request and Response objects
In Express.js, the Request (req) and Response (res) objects are key components of
/book/12:15
handling incoming HTTP requests and sending responses back to clients. These objects are passed
The res.send() method returns as arguments to callback functions in route handlers and provide numerous methods and properties
to handle various aspects of web requests and responses.
Get Book: Chapter: 12 Page: 15
Request Object (req)
3. Route parameters using Defined parameters: The Request object contains data about the incoming HTTP request, such as the URL,
query parameters, route parameters, body data, headers, and more.
• Route parameters are dynamic segments in a URL defined by a colon (:) followed by a name.
Key Properties and Methods of req:
• These parameters are part of the URL path and can be accessed using req.params.
• req.params: Contains route parameters (captured from dynamic parts of the route).
Example: • req.query: Contains query string parameters from the URL.
• req.body: Contains the body data (useful for POST, PUT, PATCH requests, with middleware
app.get('/user/:id', function(req, res) {
like body-parser).
const userId = req.params.id; // Access the route parameter 'id' • req.headers: Contains the HTTP headers sent by the client.
• req.url: The full URL of the incoming request.
6 7
• req.method: The HTTP method used for the request (GET, POST, etc.). • res.render(): Renders a view template (useful when working with templating engines like
• req.path: The path portion of the URL. Pug or EJS).
• req.cookies: Contains cookies sent by the client (requires cookie-parser middleware).
• res.set(): Sets a specific response header.
• req.ip: The IP address of the client.
• res.cookie(): Sets a cookie (requires cookie-parser middleware).
Example: • res.end(): Ends the response without any data (useful when you want to just terminate the
connection).
Setting Header:
01 var express== require('express');
In Express.js, it can set response headers using the Response (res) object. Headers provide meta-
02 var app express(); information about the response and are typically used to control caching, content type, encoding,
03 app.listen(80); and other details. The headers must be set before sending the response body to the client.
14 console.log("Secure:\t”+req.secure);
15 console.log("UTFB:\t”+req.acceptaCharset('utf8')); :
Setting the status:
16 console.log("Connection:”+req.get('connection'));
The status code in an HTTP response indicates the outcome of the request—whether it succeeded,
17 console.log ("Headers:”+ JSON.stringify(req.headers,null,2)); encountered an error, or something else.
18 res.send("User Request"); The .status() method on the response (res) object is used to set this status code in Express. This
method is chained to other methods like .send() or .json(), which send the response body back to
19 });
the client. By explicitly setting the status code, you provide a clear and standardized way for clients
to interpret the result of their requests.
Example status codes include:
• res.status(200) //200 for successful requests (OK)
• res.status(400) //400 for client errors (Bad Request)
• res.status(404) //404 for resources not found (Not Found)
• res.status(500) //500 for server errors (Internal Server Error)
8 10
Sending JSON Data: Class Basics
A class in TypeScript is defined using the class keyword, followed by the class name
Express facilitates sending JSON by providing the json() and jsonp() methods on the Response
and a set of properties and methods inside its body.
object. These methods use a similar syntax as send () except that the body is a JSON stringifiable
A basic class has a constructor method that initializes its properties, and you can add
JavaScript object:
other methods to define the class’s behavior.
res.json(status, [object])
Example:
res.json([body])
class Person {
res.jsonp(status, [object))
name: string;
res.jsonp([object])
age: number;
Example:
constructor(name: string, age: number) {
app.get('/user/:id', function(req, res) {
this.name = name;
const userId = req.params.id;
this.age = age;
// Sending JSON response
}
res.status(200).json({
greet() {
id: userId,
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
message: 'User details retrieved successfully'
}
});
}
});
const person1 = new Person("Alice", 25);
Redirecting to Another URL:
person1.greet(); // Output: Hello, my name is Alice and I am 25 years old.
In Express.js, redirecting is a common practice when you want to send users from one route to
• The Person class has two properties: name and age, both defined with specific types.
another. This can happen when URLs change, after a successful form submission, or as part of a
• The constructor is used to initialize these properties when a new Person object is created.
login/logout flow. The res.redirect() method is used to send a client to a new URL, either
temporarily or permanently. • The greet method defines a behaviour that logs a message to the console.
app.get('/old-route', function(req, res) { Inheritance is a fundamental concept in object-oriented programming (OOP) that
allows a class (called a subclass or child class) to inherit properties and methods from another
// Redirect the client to a new route class (called a superclass or parent class). Inheritance promotes code reuse, allowing developers
to create new classes based on existing ones while adding or modifying specific functionalities.
res.redirect('/new-route');
In TypeScript, inheritance is implemented using the extends keyword. The child class
});
can access public and protected members of the parent class and can also override methods to
IV. Angular provide specialized behavior.
Angular is a popular open-source web application framework maintained by Google. Key Concepts of Class Inheritance
It's designed for building dynamic, single-page applications (SPAs) with a focus on code
1. Base Class (Parent Class): The class from which properties and methods are inherited.
modularity, testability, and maintainability. Angular uses a component-based architecture, where
each component represents a part of the user interface (UI) that can be reused across the application. 2. Derived Class (Child Class): The class that inherits from the base class. It can extend
or override the properties and methods of the base class.
11 14
3. Constructor Chaining: The child class can call the parent class's constructor using the V.Angular Components
super() function.
A component in Angular is a key building block of an Angular application. It is a
Example: reusable unit of an Angular application formed by a template and a class that controls a section
of the screen.
// Base Class
The class includes attributes and methods that describe the component’s behavior, while
class Animal {
the template determines the component’s structure and appearance on the screen.
name: string;
Components are used to divide a huge application into smaller, more manageable, and
constructor(name: string) { self-contained components. They communicate with one another via inputs, outputs, and
services, resulting in a more modular and easy-to-maintain application.
this.name = name;
}
speak(): void {
console.log(`${this.name} makes a noise.`);
}
}
// Derived Class
class Dog extends Animal {
constructor(name: string) {
super(name); // Call the constructor of the parent class
}
Each component consists of:
speak(): void {
• HTML template: Defines the structure of the view.
console.log(`${this.name} barks.`);
• TypeScript class: Handles the logic and data for the component.
}
• CSS styles: Defines the styling for the view (optional).
}
Structure of an Angular Component
// Creating an instance of the derived class
An Angular component is made up of four key parts:
const dog = new Dog("Buddy");
1. Decorator: A special TypeScript syntax that provides metadata about the component.
dog.speak(); // Output: Buddy barks.
2. Template: The HTML structure of the view that defines how the component will
• Animal is the base class, which has a property name and a method speak().
render on the screen.
• Dog is a derived class that extends Animal. It overrides the speak() method to provide a
specific implementation for dogs. 3. Class: The TypeScript logic of the component that handles data and events.
• The super(name) call in the Dog constructor invokes the constructor of the Animal class 4. Styles: Optional CSS to style the view.
to initialize the name property.
Example:
// app.component.ts (Class)
15 18
import { Component } from '@angular/core'; 3. Lifecycle Hooks: While the constructor is used for initialization, it is often best
practice to perform component logic in lifecycle hooks like ngOnInit.
Structure of a Constructor in an Angular Component
@Component({
A typical constructor in an Angular component follows this structure:
selector: 'app-root', // The HTML tag to use in templates
Example: simple component that displays the date
templateUrl: './app.component.html', // Path to the HTML template
import { Component } from '@angular/core';
styleUrls: ['./app.component.css'] // Path to the CSS styles
})
@Component({
export class AppComponent {
selector: 'app-date-display',
title = 'Angular Component Example'; // Property
templateUrl: './date-display.component.html',
}
styleUrls: ['./date-display.component.css']
• The @Component decorator is used to provide metadata for the component.
• selector: The custom HTML tag that will represent this component in the view (<app- })
root></app-root>).
export class DateDisplayComponent {
• templateUrl: Path to the external HTML template.
• styleUrls: Path to the external CSS styles. currentDate: string;
This is the HTML view for the component, which displays the title property from the // Initialize currentDate with the current date
TypeScript class. this.currentDate = new Date().toLocaleDateString();
Styles (app.component.css): }
h1 { }
color: blue; Using External Templates:
} Using external templates in Angular components helps maintain a clean separation between the
This CSS will style the heading in the template. component logic (TypeScript) and the view (HTML). This practice is especially beneficial for
larger applications where components can become complex.
Using Constructors in Angular Components
Under the component decorator, place the keyword templateurl followed by the path from the
In Angular, constructors are special methods used for initializing class members and root of the application to your template HTML file. Here is an example.
setting up dependencies for the component. The constructor is invoked when an instance of
the class is created, making it an ideal place to perform any setup required for the component. @Component({
2. Dependency Injection: Angular uses a dependency injection (DI) system that allows })
you to inject services or other dependencies directly into the constructor.
19 20
use the keyword styleurls to tell the component about external stylesheets. The
difference with the external stylesheets is that pass in an array of one or more stylesheets. The
following example shows how to import external stylesheets:
@Component ({
selector: 'my-app’,
templateUrl: /view.example.html"
styleUrls: ["./stylesl.css", "./styles2.css"]
})
21