UNIT IV Notes - Removed
UNIT IV Notes - Removed
Implementing Express in Node.js - Configuring routes - Using Request and Response objects
- Angular - Typescript - Angular Components - Expressions - Data binding - Built-in
directives
1
var express=require(‘express’)
var app=express()
• express = require('express'): Imports the Express.js library.
• app = express(): Creates an Express application instance, which you will use to handle
requests and responses.
Configuring express Settings:
• It defines the environment as well as how express handles JSON parsing routing and views.
Methods to see the value of the application settings:
1. set(setting, value)
• →used to configure settings in Express application.
• →It allows the developer to control the behavior of various aspects of the app, such as view
rendering, request handling, and response formatting.
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
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.
• 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".
3
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:
• 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.
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.
• This is commonly used for filtering, sorting, or sending small amounts of data.
• 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.
5
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:
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'
6
res.send('User ID: ' + userId);
});
• URL Request: /user/123
• Route Parameter: id
• Extracted Value: 123 → res.send() method returns Get user: 123
7
• 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);
14 console.log("Secure:\t”+req.secure);
15 console.log("UTFB:\t”+req.acceptaCharset('utf8')); :
16 console.log("Connection:”+req.get('connection'));
18 res.send("User Request");
19 });
8
• 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.
10
Sending JSON Data:
Express facilitates sending JSON by providing the json() and jsonp() methods on the Response
object. These methods use a similar syntax as send () except that the body is a JSON stringifiable
JavaScript object:
res.json(status, [object])
res.json([body])
res.jsonp(status, [object))
res.jsonp([object])
Example:
app.get('/user/:id', function(req, res) {
const userId = req.params.id;
// Sending JSON response
res.status(200).json({
id: userId,
message: 'User details retrieved successfully'
});
});
Redirecting to Another URL:
In Express.js, redirecting is a common practice when you want to send users from one route to
another. This can happen when URLs change, after a successful form submission, or as part of a
login/logout flow. The res.redirect() method is used to send a client to a new URL, either
temporarily or permanently.
Syntax:
app.get('/old-route', function(req, res) {
// Redirect the client to a new route
res.redirect('/new-route');
});
IV. Angular
Angular is a popular open-source web application framework maintained by Google.
It's designed for building dynamic, single-page applications (SPAs) with a focus on code
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.
11
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.`);
}
}
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.
14
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.`);
}
}
// 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.
15
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.
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.
18
import { Component } from '@angular/core';
@Component({
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.
19
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
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
})
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