0% found this document useful (0 votes)
682 views11 pages

Unit 4 - Express & Angular

1. The document discusses Express and Angular frameworks. It covers implementing Express in Node.js, configuring routes, and using request and response objects. It also covers Angular components like TypeScript, data binding, and directives. 2. Key features of Express.js include its flexibility, robust routing system, middleware support, and ability to integrate template engines. Popular frameworks like Blueprint and Sails are built on Express. 3. Configuring routes in Express involves specifying HTTP request methods, path in the URL, and applying parameters. The request and response objects provide access to request data, headers, and methods for sending responses.

Uploaded by

saitamaakaopman
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)
682 views11 pages

Unit 4 - Express & Angular

1. The document discusses Express and Angular frameworks. It covers implementing Express in Node.js, configuring routes, and using request and response objects. It also covers Angular components like TypeScript, data binding, and directives. 2. Key features of Express.js include its flexibility, robust routing system, middleware support, and ability to integrate template engines. Popular frameworks like Blueprint and Sails are built on Express. 3. Configuring routes in Express involves specifying HTTP request methods, path in the URL, and applying parameters. The request and response objects provide access to request data, headers, and methods for sending responses.

Uploaded by

saitamaakaopman
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/ 11

UNIT IV - EXPRESS AND ANGULAR

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

Implementing Express in Node.js

• Configuring Express Settings


• Starting the Express Server

Configuring Routes

• Implementing Routes
• Applying Parameters in Routes

Using Requests Objects & Response Objects

• Setting Headers
• Setting the Status
• Sending Response
• Sending JSON Responses
• Sending Files
• Sending a Download Response
• Redirecting the Response
EXPRESS JS: Fast, unopinionated, minimalist web framework for Node.js

• Express is a lightweight module that wraps the functionality of the Node.js http module in a simple-to- use interface
• Express is a node js web application framework that provides features for building web and mobile apps.
• It is used to build a single page, multipage, and hybrid web application.
• It is a layer built on the top of the Node js that helps manage servers and routes.

Version:

• Express 4.18.1
• Express 5.0 beta

Popular Node.js frameworks are built on Express:

• Express Gateway: Fully-featured and extensible API Gateway


• Blueprint: a SOLID framework for building APIs and backend services
• Kites: Template-based Web Application Framework
• Sails: MVC framework for Node.js for building production-ready apps.

Features of Express JS | Why Express JS? | Advantages:

• Minimalism & Flexibility - minimal & flexible Node.js web application framework for web & mobile app
• Robust Routing System - allows you to easily map URLs to specific functions or controllers
• Middleware Support - request handler that has access to the application's request-response cycle.
• Template Engine Integration – build dynamic content to make the application more organized &
maintainable.

Companies Using Express JS : Netflix, IBM, ebay, Uber

2 Marks

Command to install Express or npm install express


command to add the express module from the root of your project

setting up a port configuration const PORT = 3000 (or)

const PORT = process.env.PORT || 3000;

import the express module and create an instance of express or var express = require('express');
var app = express()
Starting the Express Server
app.listen(8080);
Configuring Express Settings app.enable('trust proxy');
app.disable('strict routing');
app.set('view engine', 'pug');
1. Implementing Express in Node.js
U plz write this in Paragraph | For understanding it’s in tabular form

Steps Description Coding

Create a new directory for the project and mkdir express-example


navigate into it: cd express-example
1. Set Up the
Project Initialize your project with npm init and
follow the prompts to create a npm init
package.json file.

2. Install
Install Express using npm: npm install express
Express
Create a file (e.g., app.js) and implement // File Name: app.js
the following Express application:

Import the Express module. const express = require('express');

Create an instance of the Express application const app = express();


using express(). const PORT = 3000;
3. Create a
Express app.get('/', (req, res) => {
Application Define a route for the root path ('/') that sends a
res.send('Hello world!');
response of "Hello, Express!" when accessed.
});

Set up the server to listen on port 3000.


app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});

Save the changes and run the


4. Run the
application using the following
Application node app.js
command

Output Screen
Coding Without Explanation
2. Configuring Routes in Express JS
• Routing in Express JS is the process of specifying how an application replies to a client request to a
specific endpoint or URL.
• To run a function upon request for a certain route, route handlers are used.
• Syntax : app.method(path, [callback . . .], callback)
• Two parts are there in defining routes:
1. HTTP Request Method:
• The HTTP request method determines the type of operation the client is requesting.
• Different HTTP request methods are used for different purposes:
 GET : retrieving data from the server.
 POST : submitting data to be processed to a specified resource.
 PUT : updating a resource on the server.
 DELETE : requesting that a resource be removed or deleted.

2. Path Specified in the URL:


• The path in the URL specifies the endpoint or route on the server that the client is trying to access.
• For example:
/ : represents the root of the website.
/login : represents the login page.
/cart : represents a shopping cart page.
• There are four main methods for implementing parameters in a route:
Query string, POST params , regex. Defined parameter:
• Example :
const express = require('express'); // Import required modules
const app = express(); // Create an Express application
const port = 3000;
app.get('/', function(req, res) // Defining Routes – Server Root
{
res.send("Server Root");
});
app.get('/login', function(req, res) //Defining Routes – Login Page
{
res.send("Login Page");
});
app.get('/find', function(req, res) //Defining Routes – Find Page
{ // Applying parameters to route
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
res.send('Finding Student: Name: ' + query.name + ' Branch: ' + query.branch);
});
For example, consider the following URL: find?name = Arun & branch = IT
The res.send() method returns: Finding Student: Name : Arun Branch : IT
3. Using Request and Response objects in Express JS
• In an Express.js application, the request (req) and response (res) objects are fundamental to handling
HTTP requests and sending responses.
• Request Object (req):
• The req object represents the HTTP request and contains information about the data and
metadata of the request made by the client.
• It provides access to parameters, URL,query strings, headers, and the request body.

Example :

}); Output
Response Object(res)
• The res object represents the HTTP response that an Express app sends when it receives an HTTP request.
• It provides methods for sending a response, setting headers, and managing the response body.
Description Method Definition

get(header) Returns the value of the header specified.


Setting Headers
set(header, value) Sets the value of the header.

setHeader(name, value) Sets a single header value for the response.

send([body]) Sends the HTTP response.


Sending
Response & File
sendFile(path) Sends a file as an octet stream.

json([body]) Sends a JSON response


Sending JSON
Responses Sends JSON data without worrying about cross-
jsonp([object])
domain issues
Sending
Download download(path, [filenme], [calback]) Sends the file in the HTTP response as an attachment
Response
Redirecting the
redirect(path) Handles redirection of the request to a new location
Response
Setting the Status status(code) Sets the HTTP response status code.

End the response end() Ends the response process.


Example :
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.set('Content-Type', 'text/plain'); // 1. Setting and Getting Headers
const contentType = res.get('Content-Type');
console.log('Content-Type:', contentType);
res.setHeader('Cache-Control', 'no-store'); // 2. Alternative method for setting headers
res.send('Hello, this is a simple response!'); // 3. Sending a basic response
res.sendFile(__dirname + '/example.txt'); // 4. Sending a file
const jsonData = { message: 'This is a JSON response.' }; // 5. Sending JSON response
res.json(jsonData);
res.jsonp({ message: 'This is a JSONP response.' });
res.download(__dirname + '/example.txt', 'custom_filename.txt'); // 6. Downloading a file
res.redirect('../new-path'); // 7. Redirecting to another path
res.status(400); // 8. Setting HTTP status code
res.end(); // 9. Ending the response
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
2 marks :

How do you set the HTTP status for the response and list the different statuses?
To set the status response, use the status(number) method where the number parameter is the HTTP response status
Example :
res.status(200); // OK
res.status(300); // Redirection
res.status(400); // Bad Request
res.status(401); // Unauthorized
res.status(403); // Forbidden
res.status(500); // Server Error

Angular - Typescript - Angular Components - Expressions - Data binding – Built in directives

Angular | Features of Angular – Refer Unit 1


Angular Vs React – Refer Unit 5

What is Type Script ? | Why Type Scipt ? | Features of Type Script


• TypeScript is a syntactic superset of JavaScript which adds static typing.
• TypeScript adds syntax on top of JavaScript, allowing developers to add types.
• Angular is built on TypeScript
• TypeScript uses compile time type checking.
• It supports features like classes, interfaces, and inheritance,
• TypeScript includes generics - creation of reusable and type-safe components.
Type Script Data Types | Example
• String | var stuName: string = 'Siva’;
• Number | var age: number = 21;
• Boolean | var yes: boolean = true;
• Array | var arr:string[] = ["one", "two", "three"];
• Null | var newVar = null;
• Any | Var anyType: any = 404 ;
• Enum | Enum StuNames {Bob, John, Alex}
Angular Components
• Angular components are the building blocks used to create Angular applications.
• Angular components allow you to build self-contained UI elements for an application
• An Angular component consists of two main parts:
o decorator section , which have definition and
o class section, which defines the logic.
• The decorator section is used to configure the component, including things like the selector name and
HTML template.
• The class section enables you to give the component its logic, data, and event handlers.
This option allows you to define the HTML tag name used to add the component to the
Selector
application via HTML.

Template This option allows you to add inline HTML to define the look of the component

templateUrl This option allows you to import an external template file rather than inline HTML.

Styles This option allows you to add inline CSS to your component.

stylesUrls This option allows you to import an array of external CSS stylesheet(s
This is an array of dependency injection providers.
viewProviders It allows you to import and use Angular services that provide application functionality
such as HTTP communications.
Example :

The following section describe the most important aspects of the Angular framework and how they contribute
to make Angular a great JavaScript framework.
• Angular applications are modular and organized into cohesive units called modules.
• Modules encapsulate related components, directives, pipes, and services.
Modules
• // app.module.ts
o Import {Component} from 'angular2/core';
o Export class App{}
• Directives are JavaScript classes with metadata that defines the structure and behavior.
Directives • Directives provide the majority of UI functionality for Angular applications.
• Three major types of directives: Components , structural and attrinbutes.
Data Binding —the process of linking data from a component with what is displayed in a web page
• a process in which a component defines dependencies on other components.
Dependency • When the code is initialized, the dependent component is made available for access
Injection within the component. Angular applications make heavy use of dependency injection.
• Common use for dependency injection is consuming services.
Services in Angular are singleton objects that provide functionality and features to multiple
Services
parts of the application, promoting code reusability.
• AngularJS Expressions are used to bind data to HTML elements, allowing dynamic content rendering.
• Angular evaluates expressions and then can dynamically add the results to a web page.
• AngularJS expressions can be written inside double braces: {{ expression }}.
• AngularJS expressions can also be written inside a directive: ng-bind="expression".
• AngularJS will resolve the expression, and return the result exactly where the expression is written.
• AngularJS expressions are enclosed within double curly braces and can contain variables, literals,
operators, and method calls.
• Example: {{ 5 + 5 }}
{{ firstName + " " + lastName }}

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
// Without the ng-app directive, HTML will display the expression as it is, without solving it.

<div ng-app ng-init="a=10;b=20">


<p>My first expression: {{ 5 + 5 }}</p>
<p>Total : {{ a + b }}</p>
</div>

<div ng-app="" ng-init="firstName='John';lastName='Doe'">


<p>The full name is: <span ng-bind="firstName + ' ' + lastName"></span></p>
</div>

</body>
</html>

Output: My first expression: 10


Total : 30
The full name is: John Doe
• A pipe is a type of operator that hooks into the expression parser and modifies the results of the
expression for display in a view.
• It is used to format time or currency values.
• Syntax: {{ expression | pipe}}
• Example:
<body ng-controller="DateController">
<h1>Current Date</h1> // Uisng Builtin pipes
<p>Short Format: {{ currentDate | date:'short' }}</p>
<p>Long Format: {{ currentDate | date:'fullDate' }}</p>
</body>
--++++++++++++++++++++++++++++++++++++++++++++++++++++++
• Data binding is the process of linking data from a component with what is displayed in a web page.
• When data in the component changes, the UI rendered to the user is automatically updated.
• The different types of data binding are listed below with example:
Uses double curly braces (`{{ }}`) to directly retrieve values from the Component class
Interpolation
and display them in the template.
Property
Sets the property of an HTML element based on the value from the Component class.
Binding
Handles user inputs by binding methods or expressions in the Component class to
Event Binding
events triggered in the HTML template.
Attribute Allows setting attributes to an HTML element dynamically based on values from the
Binding Component class.
Sets CSS class names dynamically for an element based on conditions or values from
Class Binding
the Component class
Style Binding Dynamically creates inline CSS styles for an HTML element based on values from the
Component class
Two-Way
Combines property binding and event binding to achieve two-way communication,
Binding
commonly used in data entry forms to receive and display data.
with ngModel

Angular Component (app.component.ts): HTML Template (app.component.html):

import { Component } from '@angular/core'; <div>


<!-- Interpolation -->
<p>User Name: {{ userName }}</p>
@Component({
selector: 'app-root', <!-- Property Binding -->
templateUrl: './app.component.html', <input [value]="userName" />
styleUrls: ['./app.component.css']
}) <!-- Event Binding -->
export class AppComponent { <button (click)="onButtonClick()">Click me</button>
// Properties
userName: string = 'John Doe'; <!-- Attribute Binding -->
<img [src]="userAge >= 18 ? 'adult.png' : 'child.png'" alt="User Image" />
userAge: number = 25;
<!-- Class Binding -->
// Method to handle button click <div [class]="userAge >= 18 ? 'adult' : 'child'">User Status</div>
onButtonClick() {
<!-- Style Binding -->
alert('Button clicked!');
<p [style.color]="userAge >= 18 ? 'green' : 'red'">Status</p>
}
} <!-- Two-Way Binding with ngModel -->
<input [(ngModel)]="userName" placeholder="Enter name" />

</div>
In the above example:
• Interpolation ({{ }}): Displays the user's name directly in the template.
• Property Binding ([ ]): Sets the value of the input field to the user's name.
• Event Binding (( )): Calls the onButtonClick method when the button is clicked.
• Attribute Binding ([ ]): Dynamically sets the image source based on the user's age.
• Class Binding ([ ] with class): Dynamically applies the 'adult' or 'child' class based on the user's age.
• Style Binding ([ ] with style): Dynamically sets the text color based on the user's age.
• Two-Way Binding with ngModel ([(ngModel)]): Binds the input field value to both the user's name property
and the input value simultaneously.
+++++++++++++
Angular Built-in Directives
• Angular Directives are a combination of Angular template markup and supporting TypeScript code.
• It can be expressed through HTML attributes, element names, or CSS classes.
• The TypeScript directive code outlines the data and behavior for HTML elements associated with the
directive.
• During compilation, the Angular compiler processes and compiles all directives in the template DOM.
• Angular directives are markers on a DOM element that tell Angular to manipulate the element or
transform its behavior.

Description Explanation
Components Directives A directive with a template : Attribute:
Structural Directives A directive that manipulates elements in the DOM
Directive Description Example
Iterates over a collection
ngFor and renders content for <li *ngFor="let item of items">{{ item }}</li>
each item.
Conditionally renders
ngSwitch content based on matching <div [ngSwitch]="selectedOption"> ... </div>
cases.

ngSwitchCase Used within an ngSwitch <p *ngSwitchCase="'Option 1'"> You selected Option 1</p>
& block to define specific <p *ngSwitchCase="'Option 2'"> You selected Option 2 </p>
ngSwitchDefault cases. <p *ngSwitchDefault> Select an option </p>

// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<h1 *ngIf="isUserLoggedIn">Welcome, {{ userName }}!</h1>
<p *ngIf="!isUserLoggedIn">Please log in to access the content.</p> ‘,
styleUrls: ['./app.component.css']
})
export class AppComponent {
isUserLoggedIn: boolean = true;
userName: string = 'John Doe';
}
Attribute Directives A directive that manipulates the appearance and behavior of a DOM element
Directive Description Example
Implements two-way data binding,
ngModel allowing changes in the UI to <input [(ngModel)]="userName" />
update the model and vice versa.
Creates a top-level form instance
and exposes form-related directives,
ngForm <form #myForm="ngForm" ngSubmit)="submitForm"> ... </form>
allowing form validation and
submission.
Binds CSS styles dynamically based
ngStyle <p [ngStyle] = " {'color': textColor, 'font-size': fontSize } "> Styled Text </p>
on expression evaluation.

******

You might also like