Cloud computing unit 5
Cloud computing unit 5
Implementing Express in Node.js - Configuring routes - Using Request and Response objects
- Angular - Typescript - Angular Components - Expressions - Data binding - Built-in
directives
Common Settings:
• view engine: Specifies the template engine (e.g., Pug, EJS).
• case sensitive routing: When set to true, /Home and /home are treated as different routes.
2. Enable(setting)
• to set a specific setting to true.
• This function is used to enable a specific setting or configuration option within the
application. This method allows to control various behaviors of the Express server.
• It’s typically used for Boolean settings that either enable or disable a feature.
• It can be thought of as equivalent to app.set(setting, true).
3. Disable(setting)
• It is a shortcut to set a specific setting to false.
• It disables a feature and can be seen as equivalent to app.set(setting, false).
2
Starting the Express server:
To begin implementing Express as the HTTP server for your Node.js application,
• need to create an instance and begin listening on a port.
var express = require('express’);
var app = express();
app.listen(8080);
• 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.
When the server is running, it listens for HTTP requests on http://localhost:8080.
• host: '127.0.0.1': specifies that the server will be accessible only from the local machine
(localhost).
• 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/
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
and secure transmission between the server and clients.
3
• http.createServer(app).listen(80); creates an HTTP server using the http module and binds it
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.
• https.createServer(options, app).listen(443);creates an HTTPS server using the https module
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.
• GET route on the root URL (/). When a client makes a GET request to http://localhost/ (or
https://localhost/), the server responds with the message "Hello from Express".
• Before the server can begin accepting requests, its need to define the routes.
• In Express.js, configuring routes is essential for defining how your application responds to
different HTTP requests (like GET, POST, PUT, DELETE). Routes specify which functions
are executed when the app receives a request to a particular URL or endpoint.
• Route describes how to handle the path portion of the URL in the http request to the express
server.
Implementing Routes:
Two parts: when defining the route
1. HTTP request method(GET or POST)
2. the path specified in the URL
functions used to implement routes for the Express server.
Syntax:
app. <method> (path, [callback .1, callback)
The <method> portion refers to the HTTP request method, such as GET or POST.
For example:
app.get(path, [middleware, ...), callback)
app.post (path, (middleware,...), callback)
• path refers to the path portion of the URL that you want to be handled by the callback function.
4
• Callback function is the request handler that handles the request and sends the response back to
the client.
• The callback function accepts a request object as the first parameter and a response object as the
second.
• When the express server receives an http request , it looks for a route that has been defined for the
appropriate HTTP method and path.
app.get('/’, function(req, res) {
res.send('Hello, World!’);
});
app.get('/about’, function(req, res) {
res.send('This is the About page.’);
});
app.post('/submit’, function(req, res) {
res.send('Data submitted successfully!’);
});
• app.get(): Defines a route handler for HTTP GET requests to the /about path.
• '/about': This is the route or endpoint. When a user visits http://yourserver.com/about, this
function will handle the request.
• function (req, res): This is the callback function that is executed when the /about route is hit.
It takes two parameters:
• req (request): Represents the incoming HTTP request.
• app.get() is used for handling HTTP GET requests, which are typically used for retrieving data
from the server.
• app.post() is used for handling HTTP POST requests, which are typically used for sending
data to the server (such as form submissions).
• 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.
5
app.all(‘*’,function(req,res){
// global handler for all paths
});
Applying parameters in routes:
• several ways to pass parameters to routes, which can be useful for retrieving data, processing
user input, and more.
• Starts with: A ? symbol that marks the beginning of the query string in the URL.
• Key-value pairs: Parameters are expressed as key-value pairs separated by the = symbol.
• Multiple parameters: Multiple key-value pairs are separated by &.
app.get('/find', function(req, res) {
var url_parts= url.parse(req.url, true);
var query = url_parts.query;
res.send('Finding Book: Author: ' + query.author +’Title: ‘+ query.title);
});
Example:
http://localhost:3000/find?author=John&title=AI
Query Parameters:
• author=John
• title=AI
Response: The server will respond with the text
Finding Book: Author: John Title: AI
This route handler processes a URL with query parameters (?author=John&title=AI), parses
the query string to extract the parameters, and sends back a response that displays the values
of author and title.
2. Regex Parameters:
6
In Express.js ,It can define routes with regular expressions (regex) to match more
complex patterns in the URL. This is useful when it needs more flexibility in routing, such as
matching dynamic segments of a URL or enforcing specific formats.
app.get(/^\/book\/(\w+)\:(\w+)?$/, function(req, res) {
res.send('Get Book: Chapter: + req.params [0] +
'Page: ' + req.params[1]);
});
example, consider the following URL:
/book/12:15
The res.send() method returns
Get Book: Chapter: 12 Page: 15
3. Route parameters using Defined parameters:
• Route parameters are dynamic segments in a URL defined by a colon (:) followed by a name.
• These parameters are part of the URL path and can be accessed using req.params.
Example:
app.get('/user/:id', function(req, res) {
const userId = req.params.id; // Access the route parameter 'id'
res.send('User ID: ' + userId);
});
• URL Request: /user/123
• Route Parameter: id
• Extracted Value: 123 → res.send() method returns Get user: 123
7
Example:
app.param('userid', function(req, res, next, value) {
console.log("Request with userid: + value);
next();
});
consider the following URL:
/user/4983
The userid of 4983 is parsed from the URL and the consol.log() statement displays
Request with userid: 4983
III. Using Request and Response objects
In Express.js, the Request (req) and Response (res) objects are key components of
handling incoming HTTP requests and sending responses back to clients. These objects are passed
as arguments to callback functions in route handlers and provide numerous methods and properties
to handle various aspects of web requests and responses.
Request Object (req)
The Request object contains data about the incoming HTTP request, such as the URL,
query parameters, route parameters, body data, headers, and more.
Key Properties and Methods of req:
• req.params: Contains route parameters (captured from dynamic parts of the route).
• req.query: Contains query string parameters from the URL.
• req.body: Contains the body data (useful for POST, PUT, PATCH requests, with middleware
like body-parser).
• req.headers: Contains the HTTP headers sent by the client.
• req.url: The full URL of the incoming request.
• req.method: The HTTP method used for the request (GET, POST, etc.).
• req.path: The path portion of the URL.
• req.cookies: Contains cookies sent by the client (requires cookie-parser middleware).
• req.ip: The IP address of the client.
Example:
03 app.listen(80);
8
04 app.get('/user/:userid', function (req, res) {
10
• res.status(): Sets the HTTP status code for the response (e.g., 200, 404, 500).
• res.redirect(): Redirects the client to another URL.
• res.render(): Renders a view template (useful when working with templating engines like
Pug or EJS).
• res.set(): Sets a specific response header.
• res.cookie(): Sets a cookie (requires cookie-parser middleware).
• res.end(): Ends the response without any data (useful when you want to just terminate the
connection).
Setting Header:
In Express.js, it can set response headers using the Response (res) object. Headers provide meta-
information about the response and are typically used to control caching, content type, encoding,
and other details. The headers must be set before sending the response body to the client.
11
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)
Typescript:
• Angular and TypeScript form a powerful combination for building scalable, maintainable
web applications.
• Angular is a popular framework for building single-page applications (SPAs), while
TypeScript, a statically typed superset of JavaScript, serves as the programming language
used to write Angular applications.
Different Types
TypeScript provides a rich set of types, which allow developers to explicitly define and enforce the
kind of data variables, functions, and objects can hold.
1.string: Represents textual data.
Example:
var mystring: string=’some text’;
2. number: Represents numerical values, both integers and floating points.
var age: number = 25;
3. boolean: Represents a true/false value.
var yes: boolean=true;
var no:boolean=false;
4. Array Type: An indexed array is a series of separate distinct data items. It can be defined
using two syntaxes:
13
5. NULL: Represents an explicitly set null value and represents the intentional absence of any
value.
Using null is better than assigning a value of o or an empty string (“ “) because those may be valid
values for the variable. By assigning null to a variable, can assign no value and check against null
inside the code, like this:
var newvar = var;
6.Any: Allows any type of value (disables type-checking).
Var anyType: any "String Assigned";
Var anyType = 404;
Var anyType = True;
7.void: Represents the absence of a value, commonly used for functions that don’t return a value
void is used when declaring a function, don't want to have a return value. The example is a
function of type void:
function empty(): void {document.write("code goes here");}
8.Enum: Enums allow you to define a set of named constant values.
enum Direction {
Up,
Down,
Left,
Right }
var x=Direction.Up // var x equal to the number 0
var y= Direction[0] // var y equal to the string up
Understanding Interfaces:
Interfaces in TypeScript are a powerful way to define the structure of an object or class.
They serve as contracts that enforce the shape, properties, and types that an object or class should
adhere to. Interfaces allow TypeScript to catch errors early, as they ensure that the implementing
objects or classes follow the expected structure.
Keyword interface is used followed by the structure that objects to follow
Example:
14
interface person {
name: string;
age: number;
}
var user: Person = { name: "Alice", age: 25, };
• The Person interface defines the structure for a person object, which must have a name
property of type string and an age property of type number.
• The user variable must conform to this structure to avoid type errors.
•
Implementing classes:
Classes in TypeScript are blueprints for creating objects. They encapsulate data
(properties) and behavior (methods) within a structured unit. TypeScript classes are similar to classes
in other object-oriented programming languages, but with added support for type checking and
interfaces.
In TypeScript, classes are enhanced by features like inheritance, access modifiers (such
as private, protected, and public), interfaces, and more, making them powerful tools for building
scalable, maintainable applications.
Class Basics
A class in TypeScript is defined using the class keyword, followed by the class name
and a set of properties and methods inside its body.
A basic class has a constructor method that initializes its properties, and you can add
other methods to define the class’s behavior.
Example:
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
15
}
const person1 = new Person("Alice", 25);
person1.greet(); // Output: Hello, my name is Alice and I am 25 years old.
• The Person class has two properties: name and age, both defined with specific types.
• The constructor is used to initialize these properties when a new Person object is created.
• The greet method defines a behaviour that logs a message to the console.
Class Inheritance:
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
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.
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
provide specialized behavior.
Key Concepts of Class Inheritance
1. Base Class (Parent Class): The class from which properties and methods are inherited.
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.
3. Constructor Chaining: The child class can call the parent class's constructor using the
super() function.
Example:
// Base Class
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
speak(): void {
console.log(`${this.name} makes a noise.`);
}
}
16
// Derived Class
class Dog extends Animal {
constructor(name: string) {
super(name); // Call the constructor of the parent class
}
speak(): void {
console.log(`${this.name} barks.`);
}
}
// Creating an instance of the derived class
const dog = new Dog("Buddy");
dog.speak(); // Output: Buddy barks.
• Animal is the base class, which has a property name and a method speak().
• Dog is a derived class that extends Animal. It overrides the speak() method to provide a
specific implementation for dogs.
• The super(name) call in the Dog constructor invokes the constructor of the Animal class
to initialize the name property.
Implementing Modules:
Modules in TypeScript are a way to organize and encapsulate code. It is used to split
the application into separate, manageable parts that can be imported and exported as needed.
This enhances code reusability, maintainability, and collaboration among developers.
Key Concepts of TypeScript Modules
1. Module Declaration: Any TypeScript file can be treated as a module if it contains at
least one import or export statement. This makes the file a separate scope for variables
and functions.
2. Exporting Modules: You can export variables, functions, classes, or interfaces from a
module so they can be used in other modules.
3. Importing Modules: You can import exported members from other modules to use
them in your current module.
17
The following example splits the person class into two separate modules:
module Person {
export interface PersonInterface {
name: string;
hungry: boolean)
feed():
}
}
/// <reference path "Person.te" />
module Person{
export class Person implements PersonInterface {
name: string;
age: number;
hungry: boolean true;
constructor (name: string, age?: number) {
this.name =name;
this.age= age;
}
feed() {
this.hungry= false;
return 'Yummy!';
}
}
}
var Brendan =newPerson("Brendan", 21);
In this example, the root module has the interface for Person. The submodule starts by using
/// <reference path="Person.ts" /> to point to the root module so it can have access to the
PersonInterface interface. The example then proceeds to build the Person class submodule.
18
Understanding Functions:
Functions are fundamental building blocks in TypeScript (and JavaScript) that is used
to encapsulate reusable code and define a set of instructions that can be executed whenever
needed, providing structure and modularity to your code.
Key Concepts of Functions
1. Function Declaration: The basic way to define a function.
2. Function Expression: Functions can be defined as expressions and assigned to
variables.
3. Arrow Functions: A more concise syntax for writing functions, introduced in ES6.
4. Parameters and Arguments: Functions can accept inputs (parameters) and return outputs
(results).
5. Return Types: You can specify the type of value that a function returns.
6. Optional and Default Parameters: Functions can have optional parameters and
parameters with default values.
7. Rest Parameters: A way to handle an indefinite number of arguments as an array.
8. Function Overloading: Allowing functions to have multiple signatures.
Example:
function hello(x: string, y: string): string{
Return x+’ ‘+ y;
}
V.Angular Components
A component in Angular is a key building block of an Angular application. It is a
reusable unit of an Angular application formed by a template and a class that controls a section
of the screen.
The class includes attributes and methods that describe the component’s behavior, while
the template determines the component’s structure and appearance on the screen.
19
Components are used to divide a huge application into smaller, more manageable, and
self-contained components. They communicate with one another via inputs, outputs, and
services, resulting in a more modular and easy-to-maintain application.
@Component({
20
selector: 'app-root', // The HTML tag to use in templates
templateUrl: './app.component.html', // Path to the HTML template
styleUrls: ['./app.component.css'] // Path to the CSS styles
})
export class AppComponent {
title = 'Angular Component Example'; // Property
}
• 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>).
• templateUrl: Path to the external HTML template.
• styleUrls: Path to the external CSS styles.
Building Template (app.component.html):
<h1>{{ title }}</h1> <!-- The title property is bound using interpolation -->
This is the HTML view for the component, which displays the title property from the
TypeScript class.
Styles (app.component.css):
h1 {
color: blue;
}
This CSS will style the heading in the template.
Using Constructors in Angular Components
In Angular, constructors are special methods used for initializing class members and
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.
Key Concepts
1. Initialization: Constructors can be used to initialize properties of a component.
2. Dependency Injection: Angular uses a dependency injection (DI) system that allows
you to inject services or other dependencies directly into the constructor.
3. Lifecycle Hooks: While the constructor is used for initialization, it is often best
practice to perform component logic in lifecycle hooks like ngOnInit.
21
Structure of a Constructor in an Angular Component
A typical constructor in an Angular component follows this structure:
Example: simple component that displays the date
import { Component } from '@angular/core';
@Component({
selector: 'app-date-display',
templateUrl: './date-display.component.html',
styleUrls: ['./date-display.component.css']
})
export class DateDisplayComponent {
currentDate: string;
constructor() {
// Initialize currentDate with the current date
this.currentDate = new Date().toLocaleDateString();
}
}
Using External Templates:
Using external templates in Angular components helps maintain a clean separation between the
component logic (TypeScript) and the view (HTML). This practice is especially beneficial for
larger applications where components can become complex.
Under the component decorator, place the keyword templateurl followed by the path from the
root of the application to your template HTML file. Here is an example.
@Component({
selector: 'my-app’,
templateUrl: /view.example.html
})
22
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"]
})
23
VI. EXPRESSIONS
Expressions in AngularJS are used to bind application data to HTML. The expressions are resolved
by AngularJS and the result is returned back to where the expression is written. The expressions in
AngularJS are written in double braces: {{ expression }}. They behave similar to ng-bind directives:
ng-bind=”expression”.
Syntax:
{{ expression }}
Example 1:
This example displays the name that we feed in the ng-init directive.
<!DOCTYPE html>
<html>
<head>
<script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<title>AngularJS Expression</title>
</head>
<body style="text-align:center">
24
<h1 style="color:green">Good Morning</h1>
<h3>AngularJS Expressions</h3>
<div ng-app=""ng-init="name=''Hello">
<p> {{ name }} is a portal for geeks.</p>
</div>
</body>
</html>
String interpolation
In general, String interpolation is the process of formatting or manipulating strings. In Angular,
Interpolation is used to display data from component to view (DOM). It is denoted by the
expression of {{ }} and also known as mustache syntax.
Let’s create a simple string property in component and bind the data to view.
export class TestComponent implements OnInit
{ appName = "My first app in Angular 8";
}
Move to test.component.html file and add the below code −
<h1>{{appName}}</h1>
Add the test component in your app.component.html file by replacing the existing content as
follows −
<app-test></app-test>
25
Finally, start your application (if not done already) using the below command − ng serve
OUTPUT :
Property binding
Property binding is used to bind the data from property of a component to DOM elements. It is
denoted by [].
Let’s understand with a simple example.
Add the below code in test.component.ts file.
export class TestComponent
{ userName:string = "Peter";
}
Add the below changes in view test.component.html,
<input type="text" [value]="userName">
Here,
userName property is bind to an attribute of a DOM element <input> tag. Finally, start your
application (if not done already) using the below command − ng serve
26
Attribute binding
Attribute binding is used to bind the data from component to HTML attributes. The syntax is as
follows −
<HTMLTag [attr.ATTR]="Component data">
For example,
<td [attr.colspan]="columnSpan"> ... </td>
Let’s understand with a simple example.
Add the below code in test.component.ts file.
export class TestComponent
{ userName:string = "Peter";
}
Add the below changes in view test.component.html,
<input type="text" [value]="userName">
Here,
userName property is bind to an attribute of a DOM element <input> tag. Finally, start your
application (if not done already) using the below command − ng serve
27
Class binding
Class binding is used to bind the data from component to HTML class property. The syntax is as
follows −
<HTMLTag [class]="component variable holding class name">
Class Binding provides additional functionality. If the component data is boolean, then the class will
bind only when it is true. Multiple class can be provided by string (“foo bar”) as well as Array of
string. Many more options are available.
For example,
<p [class]="myClasses">
Let’s understand with a simple example.
Add the below code in test.component.ts file,
export class TestComponent
{ myCSSClass = "red"; applyCSSClass = false;
}
Add the below changes in view test.component.html.
p [class]="myCSSClass">This paragraph class comes from *myClass* property </p>
<p [class.blue]="applyCSSClass">This paragraph class does not apply</p>
Add the below content in test.component.css.
.red {
28
color: red;
}
.blue {
color: blue;
}
Finally, start your application (if not done already) using the below command − ng serve The final
output will be as shown below −
Style binding
Style binding is used to bind the data from component into HTML style property. The syntax is as
follows −
<HTMLTag [style.STYLE]="component data">
For example,
<p [style.color]="myParaColor"> ... </p>
Let’s understand with a simple example.
Add the below code in test.component.ts file.
myColor = 'brown';
Add the below changes in view test.component.html.
<p [style.color]="myColor">Text color is styled using style binding</p> Finally, start your
application (if not done already) using the below command − ng serve The final output will be
as shown below −
29
Two-way data binding
Two-way data binding is a two-way interaction, data flows in both ways (from component to views
and views to component). Simple example is ngModel. If you do any changes in your property (or
model) then, it reflects in your view and vice versa. It is the combination of property and event
binding.
NgModel
NgModel is a standalone directive. ngModel directive binds form control to property and property
to form control. The syntax of ngModel is as follows −
<HTML [(ngModel)]="model.name" />
For example,
<input type="text" [(ngModel)]="model.name" />
Let’s try to use ngModel in our test application.
Configure FormsModule in AppModule (src/app/app.module.ts)
VIII. ANGULARJS DIRECTIVES :
AngularJS facilitates you to extend HTML with new attributes. These attributes are called
directives.
There is a set of built-in directive in AngularJS which offers functionality to your applications. You
can also define your own directives.
Directives are special attributes starting with ng- prefix. Following are the most common directives:
31
ng-repeat directive
ng-repeat directive repeats html elements for each item in a collection. In following example, we've
iterated over array of countries.
2. ...
3. <p>List of Countries with locale:</p>
4.
5. <ol>
6. <li ng-repeat = "country in countries">
7. {{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
8. </li>
9. </ol>
Directive Description
ng-change It specifies an expression to evaluate when content is being changed by the user.
ng-class-even It is same as ng-class, but will only take effect on even rows.
ng-class-odd It is same as ng-class, but will only take effect on odd rows.
32
ng-controller It defines the controller object for an application.
33