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

UNIT IV Notes - Removed

Uploaded by

p3727207
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

UNIT IV Notes - Removed

Uploaded by

p3727207
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

UNIT IV

EXPRESS AND ANGULAR

Implementing Express in Node.js - Configuring routes - Using Request and Response objects
- Angular - Typescript - Angular Components - Expressions - Data binding - Built-in
directives

I. Implementing Express in Node.js


Express:
• Express refers to Express.js, a minimal and flexible Node.js web application
framework.
• It is used to build web applications and APIs quickly and efficiently. It simplifies the
process of building server-side web applications and APIs by providing robust tools and
features. Express is commonly used in full-stack JavaScript development because it
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
full-stack development technologies.
how Express fits in the full-stack environment:
1.Server-Side Framework: Express is used on the back-end .
It manages the routing (handling URLs and HTTP requests), middleware (handling processes
like authentication, validation, etc.), and communication between the client and the database.
2.Handling Requests and Responses: to define how the application should respond to
different HTTP requests (GET, POST, PUT, DELETE).
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,
Angular) to communicate with the back-end server.
Getting Started with Express:
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.
• Add the express module
npm install express
• Create an instance class to act as the http server for node.js application.

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).

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();

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.

var express = require('express');


var https = require('https');
var http = require('http');
var fs = require('fs');
var app = express();
var options = {
host: '127.0.0.1’,
key: fs.readFileSync('ssl/server.key’),
cert: fs.readFileSync('ssl/server.crt')
};
http.createServer (app).listen(80);
https.createServer (options, app).listen(443);
app.get('/', function(req, res) {
res.send('Hello from Express');
});

• 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".

II. CONGIGURING ROUTES


• Before the server can begin accepting requests, its need to define the routes.

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:

• req (request): Represents the incoming HTTP request.

• res (response): Represents the outgoing HTTP response


• res.send('This is the About page.'): Sends a response with the message "This is the About
page." back to the client.

• 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.

• Each method allows different types of data to be included in the request.


1. Query String Parameters

• 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.

• Multiple parameters: Multiple key-value pairs are separated by &.


app.get('/find', function(req, res) {
var url_parts= url.parse(req.url, true);

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

4. Applying callback function for defined parameters


When parsing the URL if Express finds a parameter that has a callback registered it
calls the parameter’s callback function before calling the route handler. More than one call back
function can be registered for a route.
app.param() method is used to register a callback function. It accepts the defined
parameter as the first argument and then a callback function that receives the request , response ,
next and value parameter.
app.param(param,function(req,res,next,vakue){});
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.

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:

01 var express== require('express');

02 var app express();

03 app.listen(80);

04 app.get('/user/:userid', function (req, res) {

05 console.log ("URL:\t “+req.originalurl);

06 console.log ("Protocol: "+req.protocol);

07 console.log ("IP:\t “+req.ip);

08 console.log ("Path:\t”+ req.path);

09 console.log ("Host:\t “+req.host):

10 console.log ("Method:\t”+ req.method);

11 console.log ("Query:\t “+JSON.stringify(req.query));

12 console.log ("Fresh:\t “+req.fresh);

13 console.log ("Stale:\t “+req.stale);

14 console.log("Secure:\t”+req.secure);

15 console.log("UTFB:\t”+req.acceptaCharset('utf8')); :

16 console.log("Connection:”+req.get('connection'));

17 console.log ("Headers:”+ JSON.stringify(req.headers,null,2));

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.

Setting the status:


The status code in an HTTP response indicates the outcome of the request—whether it succeeded,
encountered an error, or something else.
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
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)

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.

Each component consists of:


• HTML template: Defines the structure of the view.
• TypeScript class: Handles the logic and data for the component.
• CSS styles: Defines the styling for the view (optional).
Structure of an Angular Component
An Angular component is made up of four key parts:
1. Decorator: A special TypeScript syntax that provides metadata about the component.
2. Template: The HTML structure of the view that defines how the component will
render on the screen.
3. Class: The TypeScript logic of the component that handles data and events.
4. Styles: Optional CSS to style the view.
Example:
// app.component.ts (Class)

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

You might also like