Full Stack UNIT 4
Full Stack UNIT 4
SYLLABUS:
Implementing Express in Node.js - Configuring routes -
Using Request and Response objects - Angular -
Typescript - Angular Components - Expressions - Data
binding - Built-in directives
Express.js:
Logo :
Written in JavaScript
Platform Node.js
Website expressjs.com
Features
Robust routing
Concentrate on high-performance
HTTP helpers (redirection, caching, etc)
Installing Express:
Firstly, install the Express framework globally using NPM so that it can
be used to create a web application using node terminal.
Save the above code in a file named server.js and run it with the
following command.
$ node server.js
You will see the following output −
Example app listening at http://0.0.0.0:8081
Open http://127.0.0.1:8081/ in any browser to see the following result.
Express.js Routing:
Routing is made from the word route. It is used to determine the specific
behavior of an application. It specifies how an application responds to a
client request to a particular route, URI or path and a specific HTTP
request method (GET, POST, etc.). It can handle different types of HTTP
requests.
Let's take an example to see basic routing.
Using middleware
Application-level middleware
Router-level middleware
Error-handling middleware
Built-in middleware
Third-party middleware
WHAT IS CORS MIDDLWARE ?
WHAT IS CSRF MIDDLWARE ?
Application-level middleware:
Bind application-level middleware to an instance of the app object by
using the app.use() and app.METHOD() functions, where METHOD is
the HTTP method of the request that the middleware function handles
(such as GET, PUT, or POST) in lowercase.
Router-level middleware:
Router-level middleware works in the same way as application-level
middleware, except it is bound to an instance of express.Router().
const router = express.Router()
Error-handling middleware:
Define error-handling middleware functions in the same way as
other middleware functions, except with four arguments instead
of three, specifically with the signature (err, req, res,
next)):
Built-in middleware:
Starting with version 4.x, Express no longer depends on Connect. The
middleware functions that were previously included with Express are
now in separate modules; see the list of middleware functions.
Third-party middleware
Use third-party middleware to add functionality to Express apps.
Install the Node.js module for the required functionality, then load it in
your app at the application level or at the router level.
The following example illustrates installing and loading the cookie-
parsing middleware function cookie-parser.
File: routing_example.js
Now, you can see the result generated by server on the local host
http://127.0.0.1:8000
Output:
This can read the pattern like abcd, abxcd, ab123cd, and so on.
req.accepts (types)
It is used to the check content types are acceptable, based on the request
accept HTTP header field.
Example :
req.accepts('html');
//=>?html?
req.accepts('text/html');
// => ?text/html?
req.get(field)
req.is(type)
Example :
// With Content-Type: text/html; charset=utf-8
req.is('html');
req.is('text/html');
req.is('text/*');
// => true
req.param(name [, defaultValue])
req.param method is used to fetch the value of param name when present.
Example :
// ?name=sonia
req.param('name')
// => "sonia"
// POST name=sonia
req.param('name')
// => "sonia"
// /user/soniafor /user/:name
req.param('name')
// => "sonia"
Response Object
The response object specifies the HTTP response when an Express app
gets an HTTP request. The response is sent back to the client browser and
allows you to set new cookies value that will write to the client browser.
There are various types of response object method, these methods are
represented below :
Example :
res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);
res.append('Warning', '299 Miscellaneous warning');
Response Attachment Method
Syntax : res.attachment(‘path/to/js_pic.png’);
Example :
res.attachment('path/to/js_pic.png'); .
It is used to set a cookie name to value. The value can be a string or object
converted to JSON.
Example :
res.cookie('name', 'alish', { domain: '.google.com', path: '/admin',
secure: true });
res.cookie('Section', { Names: [sonica,riya,ronak] });
res.cookie('Cart', { items: [1,2,3] }, { maxAge: 900000 });
Example:
res.download('/report-12345.pdf');
Example :
res.end();
res.status(404).end();
Syntax : res.get(field)
Example :
res.get('Content-Type');
Syntax : res.json([body])
Example :
res.json(null)
res.json({ name: 'alish' })
Example :
// send the rendered view to the client
res.render('index');
// ...
});
Syntax : res.status(code)
Example :
res.status(403).end();
res.status(400).send('Bad Request');
Syntax : res.type(type)
res.type method sets the content-type HTTP header to the MIME type.
Example :
res.type('.html'); // => 'text/html'
res.type('html'); // => 'text/html'
res.type('json'); // => 'application/json'
res.type('application/json'); // => 'application/json'
res.type('png'); // => image/png:
Angular :
Why Angular?
Limitations of Angular :
TypeScript :
TypeScript lets you write JavaScript the way you really want to. TypeScript is a
typed superset of JavaScript that compiles to plain JavaScript. TypeScript is
pure object oriented with classes, interfaces and statically typed like C# or Java.
The popular JavaScript framework Angular 2.0 is written in TypeScript.
Mastering TypeScript can help programmers to write object-oriented programs
and have them compiled to JavaScript, both on server side and client side.
TypeScript allows specifying the types of data being passed around within the
code, and has the ability to report errors when the types don't match.
For example, TypeScript will report an error when passing a string into a
function that expects a number. JavaScript will not.
Paradigm Multi-
paradigm: functional, generic, imperative, object-
oriented
Designed by Microsoft
Developer Microsoft
Components of TypeScript :
Language
The TypeScript Compiler
The TypeScript Language Service
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.
The above image gives the tree structure of classification. There’s a root
component, which is the AppComponent, that then branches out into
other components creating a hierarchy.
Here are some of the features of Angular Component:
The above image shows an App component, which is a pure TypeScript class
decorated with the “@Component” decorator. The metadata object provides
properties like selector, templateUrl, and so on—the templateUrL points to an
HTML file that defines what you see on your application.
constructor() { }
printMessage() = {
console.log(this.message)
}
}
Component properties and methods can bind with the view (HTML template)
using Data Binding.
2. Template :
The template defines the view of the component. It is a combination of
regular HTML and Angular template syntax that alters the regular HTML
based on the state and logic of the application and DOM data.
Print message
</button>
3. Metadata :
Metadata Provides additional information about the component to Angular.
Angular uses this information to process the class. The class immediately below
the @Component decorator is the component class. The component decorator
specifies the metadata for the component class of the Angular component.
A component’s metadata stores the information to obtain the major building blocks
required to create and present the component and its view. Angular reads the
metadata and connects the corresponding HTML template with the component
and configures how the component can be referenced in HTML and what services
it requires.
CONFIGURATION
DETAILS
OPTIONS
@Component({
selector: 'app-hello',
template: '
Print message
</button>
',
styles: [‘./hello-app.component.css’]
})
/* . . . */
AngularJS 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>
<title>AngularJS Expression</title>
</head>
<body style="text-align:center">
<h1 style="color:green">GeeksforGeeks</h1>
<h3>AngularJS Expressions</h3>
<div ng-app=""ng-init="name='GeeksforGeeks'">
</div>
</body>
</html>
OUTPUT :
Data Binding :
Data binding deals with how to bind your data from component to HTML DOM
elements (Templates). We can easily interact with application without worrying
about how to insert your data. We can make connections in two different ways one
way and two-way binding.
One-way data binding
One-way data binding is a one-way interaction between component and its
template. If you perform any changes in your component, then it will reflect the
HTML elements. It supports the following types −
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.
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 {
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 −
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)
Working example
Let us implement all the concept learned in this chapter in our ExpenseManager application.
Create an application
Use below command to create the new application.
cd /path/to/workspace
ng new expense-manager
Here,
new is one of the command of the ng CLI application. It will be used to create new application.
It will ask some basic question in order to create new application. It is enough to let the
application choose the default choices. Regarding routing question as mentioned below,
specify No.
cd expense-manager
Let us start the application using below comman.
ng serve
Let us fire up a browser and opens http://localhost:4200. The browser will show the
application as shown below −
Let us change the title of the application to better reflect our application.
Open src/app/app.component.ts and change the code as specified below −
@Component({
selector: 'app-expense-entry',
templateUrl: './expense-entry.component.html',
styleUrls: ['./expense-entry.component.css']
})
export class ExpenseEntryComponent implements OnInit {
title: string;
constructor() { }
ngOnInit() {
this.title = "Expense Entry"
}
}
Update template, src/app/expense-entry/expense-entry.component.html with below
content.
AngularJS Directives :
AngularJS facilitates you to extend HTML with new attributes. These attributes are
called directives.
Directives are special attributes starting with ng- prefix. Following are the most
common directives:
ng-app directive
ng-app directive defines the root element. It starts an AngularJS Application and
automatically initializes or bootstraps the application when web page containing
AngularJS Application is loaded. It is also used to load various AngularJS modules in
AngularJS Application.
See this example:
ng-init directive
ng-init directive initializes an AngularJS Application data. It defines the initial values
for an AngularJS application.
In following example, we'll initialize an array of countries. We're using JSON syntax to
define array of countries.
ng-model directive:
ng-model directive defines the model/variable to be used in AngularJS Application.
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.
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.