Unit-I
Unit-I
1. Saves time: The most striking feature of web framework is that it saves time and energy
in developing any app because the developer doesn't need to worry about session
handling, error handling and authentication logic. These functions are taken care of by
web frameworks.
2. Well organized app: The web framework itself takes care of managing directories and files.
This makes the complete application well organized.
5. Security: Framework makes developers sure that the application uses good security
measurements because the framework itself takes care of it.
Web Development Framework
A web development framework is a set of tools and resources that help developers build
and manage websites, web applications, and web services.
Frameworks can help with tasks like:
Database interaction
URL routing
User authentication
Security
Push notifications
Code reusability
Generating HTML from templates
Formatting data as JSON or XML
There are two types of web frameworks:
Client-side framework: Works in the front end and manages the user interface
Server-side framework: Works in the background and ensures the website functions
smoothly
Web Development Framework
A web development framework is a collection of tools, libraries, and technologies used to
create web applications. It simplifies and standardizes the development process.
Browser-to-Webserver Communication
Browser-to-webserver communication consists of a series of requests, using the HTTP and
HTTPS protocols.
Hypertext Transfer Protocol (HTTP) is used to define communication between the browser
and the webserver.
HTTP defines what types of requests can be made as well as the format of those requests
and the HTTP response.
HTTPS adds an additional security layer, SSL/TLS, to ensure secure connections by
requiring the webserver to provide a certificate to the browser.
The user can then determine whether to accept the certificate before allowing the
connection.
There are three main types of requests that a browser will make to a webserver:
■ GET: The GET request is typically used to retrieve data from the server, such as .html
files, images, or JSON data.
■ POST: POST requests are used when sending data to the server, such as adding an item
to a shopping cart or submitting a web form.
■ AJAX: Asynchronous JavaScript and XML (AJAX) is actually just a GET or POST request
that is done directly by JavaScript running in the browser. Despite the name, an AJAX
request can receive XML, JSON, or raw data in the response.
Rendering the Browser View
The screen that the user actually views and interacts with is often made up of several
different pieces of data retrieved from the webserver.
The browser reads data from the initial URL and then renders the HTML document to build
a Document Object Model (DOM). The DOM is a tree structure object with the HTML
document as the root. The structure of the tree basically matches the structure of the HTML
document. For example, document will have html as a child, and html will have head and
body as children, and body may have div , p , or other elements as children, like this:
document
+ html
+ head
+ body
+ div
+p
Rendering the Browser View
The browser interprets each DOM element and renders it to the user’s screen to build the
webpage view. The browser often gets various types of data from multiple webserver
requests to build a webpage.
The following are the most common types of data the browser uses to render the final user
view as well as define the webpage behavior:
■ HTML files: These provide the fundamental structure of the DOM.
■ CSS files: These define how each of the elements on the page is to be styled, in terms of
font, color, borders, and spacing.
■ Client-side scripts: These are typically JavaScript files. They can provide added
functionality to a webpage, manipulate the DOM to change the look of the webpage, and
provide any necessary logic required to display the page and provide functionality.
■ Media files: Image, video, and sound files are rendered as part of the webpage.
Data: Data such as XML, JSON, or raw text can be provided by the webserver as a
response to an AJAX request. Rather than send a request back to the server to rebuild
the webpage, new data can be retrieved via AJAX and inserted into the webpage via
JavaScript.
■ HTTP headers: HTTP defines a set of headers that the browser can use and client-side
scripts to define the behavior of the webpage. For example, cookies are contained in the
HTTP headers. The HTTP headers also define the type of data in the request as well as the
type of data expected to be returned to the browser.
User Interaction
The user interacts with the browser via mice, keyboards, and touchscreens. A browser has
an elaborate event system that captures user input events and then takes the appropriate
actions.
Actions vary from displaying a popup menu to loading a new document from the server to
executing client-side JavaScript.
Webservers
A webserver’s main focus is handling requests from browsers. As described earlier, a browser
may request a document, post data, or perform an AJAX request to get data. The webserver
uses HTTP headers as well as a URL to determine what action to take. This is where things
get very different, depending on the webserver, configuration, and technologies used.
Most out-of-the-box webservers such as Apache and IIS are made to serve static files such
as .html, .css, and media files. To handle POST requests that modify server data and AJAX
requests to interact with backend services, webservers need to be extended with server-side
scripts.
A server-side script is really anything that a webserver can execute in order to perform the
task the browser is requesting. These scripts can be written in PHP, Python, C, C++, C#, Perl,
Java, ... the list goes on and on. Webservers such as Apache and IIS provide mechanisms to
include server-side scripts and then wire them up to specific URL locations requested by the
browser.
This is where having a solid webserver framework can make a big difference. It often takes
quite a bit of configuration to enable various scripting languages and wire up the server-side
scripts so that the webserver can route the appropriate requests to the appropriate scripts.
Server-side scripts either generate a response directly by executing their code or connect with
other backend servers such as databases to obtain the necessary information and then use
that information to build and send the appropriate responses.
Backend Services
Backend services are services that run behind a webserver and provide data that is used to
build responses to the browser. The most common type of backend service is a database
that stores information. When a request comes in from the browser that requires
information from the database or other backend service, the server-side script connects to
the database, retrieves the information, formats it, and then sends it back to the browser.
On the other hand, when data comes in from a web request that needs to be stored in the
database, the server-side script connects to the database and updates the data.
MERN Stack
MERN is a pre-built technology stack based on JavaScript technologies.
MERN stands for MongoDB, Express, React, and Node, after the four key technologies
that make up the stack.
That's where MongoDB comes in: JSON documents created in your React.js front end can be sent to the Express.js
server, where they can be processed and (assuming they're valid) stored directly in MongoDB for later retrieval.
MEAN stack
MongoDB: A NoSQL, object-oriented database designed for use with cloud applications
Express(.js): A web application framework for Node(.js) that supports interactions between
the front end (e.g., the client side) and the database
Angular(.js): Often referred to as the “front end"; a client-side JavaScript framework used
to create dynamic web applications to work with interactive user interfaces
Node(.js): The premier JavaScript web server used to build scalable network applications
MEAN Vs MERN
The frontend framework for MEAN stack is The frontend framework for the MERN stack is The frontend framework for the full stack can be
Angular React Angular, React, or Vue.js.
The backend framework for the MEAN stack is The backend framework for the MERN stack is The backend framework for full stack can be
Express.js Express.js Express.js, Django, and Spring Boot.
It uses JavaScript as primary language for The MERN stack primary language is The full-stack primary language can be Java or
front-end and back-end JavaScript (for both front-end and back-end) Javascript or Python.
Angular’s two-way data binding can be less React’s virtual DOM often offers better The performance varies widely with stack choice
effective performance and optimization; stacks may optimize differently
Understanding the Node.js-to-AngularJS Stack Components
• The most common and the best version of this stack is the Node.js-to-AngularJS stack
comprised of MongoDB, Express, AngularJS, and Node.js.
• In the Node.js-to-AngularJS stack, Node.js provides the fundamental platform for
development.
• The backend services and server-side scripts are all written in Node.js.
• MongoDB provides the data store for the website but is accessed via a MongoDB driver
Node.js module.
• The webserver is defined by Express, which is also a Node.js module.
• The view in the browser is defined and controlled using the AngularJS framework.
AngularJS is an MVC framework in which the model is made up of JSON or JavaScript
objects, the view is HTML/CSS, and the controller is AngularJS JavaScript code.
• Figure 1.2 provides a very basic diagram of how the Node.js to AngularJS stack fits into
the basic website/web application model.
• The following sections describe each of these technologies and why they were chosen as
part of the Node.js to AngularJS stack.
Basic diagram showing where Node.js, Express, MongoDB, and AngularJS fit in the
web paradigm
Node.js
• Node.js is a development framework that is based on Google’s V8 JavaScript engine and executes it.
• You can write most—or maybe even all—of your server-side code in Node.js, including the webserver and the
server-side scripts and any supporting web application functionality.
• The fact that the webserver and the supporting web application scripts are running together in the same
server-side application allows for much tighter integration between the webserver and the scripts.
• Also, the webserver can run directly on the Node.js platform as a Node.js module, which means it’s much
easier than using, say, Apache for wiring up new services or server-side scripts.
The following are just a few reasons Node.js is a great framework:
• JavaScript end-to-end: One of the biggest advantages of Node.js is that it allows you to write both server-
and client-side scripts in JavaScript. There have always been difficulties in deciding whether to put logic in
client-side scripts or server-side scripts. With Node.js you can take JavaScript written on the client and easily
adapt it for the server and vice versa. An added plus is that client developers and server developers are
speaking the same language.
• Event-driven scalability: Node.js applies a unique logic to handling web requests. Rather than having
multiple threads waiting to process web requests, with Node.js they are processed on the same thread, using
a basic event model. This allows Node.js webservers to scale in ways that traditional webservers can’t.
• Extensibility: Node.js has a great following and very active development community. People are providing
new modules to extend Node.js functionality all the time. Also, it is very simple to install and include new
modules in Node.js; you can extend a Node.js project to include new functionality in minutes.
• Fast implementation: Setting up Node.js and developing in it are super easy. In only a few minutes you can
install Node.js and have a working webserver.
MongoDB
• MongoDB is an agile and very scalable NoSQL database.
• The name Mongo comes from the word “hu mongo us,” emphasizing the scalability and
performance MongoDB provides.
• It is based on the NoSQL document store model, which means data is stored in the
database as basically JSON objects rather than as the traditional columns and rows of a
relational database.
• MongoDB provides great website backend storage for high-traffic websites that need to
store data such as user comments, blogs, or other items because it is quickly scalable
and easy to implement.
Node.js supports a variety of database access drivers, so the data store can easily be
MySQL or some other database. However, the following are some of the reasons that
MongoDB really fits in the Node.js stack well:
■ Document orientation: Because MongoDB is document oriented, data is stored in the
database in a format that is very close to what you deal with in both server-side and client-
side scripts. This eliminates the need to transfer data from rows to objects and back.
■ High performance: MongoDB is one of the highest-performing databases available.
Especially today, with more and more people interacting with websites, it is important to
have a backend that can support heavy traffic.
■ High availability: MongoDB’s replication model makes it very easy to maintain scalability
while keeping high performance.
■ High scalability: MongoDB’s structure makes it easy to scale horizontally by sharding
the data across multiple servers.
Express
• The Express module acts as the webserver in the Node.js-to-AngularJS stack. Because it
runs in Node.js, it is easy to configure, implement, and control.
• The Express module extends Node.js to provide several key components for handling web
requests. It allows you to implement a running webserver in Node.js with only a few lines of
code.
• For example, the Express module provides the ability to easily set up destination routes
(URLs) for users to connect to. It also provides great functionality in terms of working with
HTTP request and response objects, including things like cookies and HTTP headers.
• The following is a partial list of the valuable features of Express:
• Route management: Express makes it easy to define routes (URL endpoints) that tie
directly to the Node.js script functionality on the server.
• Error handling: Express provides built-in error handling for “document not found” and
other errors.
• Easy integration: An Express server can easily be implemented behind an existing
reverse proxy system, such as Nginx or Varnish. This allows you to easily integrate it into
your existing secured system.
• Cookies: Express provides easy cookie management.
• Session and cache management: Express also enables session management and
cache management.
AngularJS
• AngularJS is a client-side framework developed by Google.
• It provides all the functionality needed to handle user input in the browser, manipulate data on the client side,
and control how elements are displayed in the browser view.
• It is written in JavaScript, with a reduced jQuery library.
• The theory behind AngularJS is to provide a framework that makes it easy to implement web applications
using the MVC framework.
• Other JavaScript frameworks could be used with the Node.js platform, such as Backbone, Ember, and Meteor.
• However, AngularJS has the best design, feature set, and trajectory at this writing.
• Here are some of the benefits AngularJS provides:
1. Data binding: AngularJS has a very clean method for binding data to HTML elements, using its powerful
scope mechanism.
2. Extensibility: The AngularJS architecture allows you to easily extend almost every aspect of the language to
provide your own custom implementations.
3. Clean: AngularJS forces you to write clean, logical code.
4. Reusable code: The combination of extensibility and clean code makes it very easy to write reusable code in
AngularJS. In fact, the language often forces you to do so when creating custom services.
5. Support: Google is investing a lot into this project, which gives it an advantage over similar initiatives that
have failed.
6. Compatibility: AngularJS is based on JavaScript and has a close relationship with jQuery.
• This makes it easier to begin integrating AngularJS into your environment and reuse pieces of your existing
code within the structure of the AngularJS framework.
JavaScript
The example below "finds" an HTML element (with id=“b"), and changes the element content
(innerHTML) to “My first JavaScript":
<html>
<body>
<h2>What Can JavaScript Do?</h2>
</body>
</html>
JavaScript Can Change HTML Content
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id=“B1">First Line of JavaScript.</p>
<p id=“B2">Second Line of JavaScript.</p>
<button type="button"
onclick='document.getElementById(“B1").innerHTML =
"Changed First Line JavaScript!"'>Click Here
First!</button>
<button type="button"
onclick='document.getElementById(“B2").innerHTML =
"Changed Second Line JavaScript!"'>Click Here
Second!</button>
</body>
</html>
JavaScript can change the style, can hide and show
hidden elements
<html><body>
<p id="b1">JavaScript can change the style of an HTML
element.</p>
<button type="button"
onclick="document.getElementById('b1').style.fontSize='35
px'">Click First!</button>
var http = require('http’);//To include a module, use the require() function with the name of the
module
http.createServer(function (req, res) {// Create an HTTP server
// Write the HTTP response header
// Status code 200 indicates success
// 'Content-Type': 'text/html' specifies the content type of the response
res.writeHead(200, {'Content-Type': 'text/html’});
res.end('Hello World!');
}).listen(8080);
Note: if 8080 is already in use and running you will get error. Change it. By default 3000 is
used in the Node.js
Create Your Own Modules
You can create your own modules and easily include them in your applications.
datetime.js datetimecall.js
var http = require('http’);
Use the exports keyword to make // Import a custom module named 'datej'
properties and methods available var dt = require('./datej');
outside the module file.
http.createServer(function (req, res) {
exports.myDateTime = res.writeHead(200, {'Content-Type':
function () { 'text/html'});
return Date(); res.write("The date and time are
}; currently: " + dt.myDateTime());
res.end();
}).listen(8080);
Read the Query String
The function passed into the http.createServer() has a req argument that represents the
request from the client, as an object
Download a Package
Downloading a package is very easy.
Open the command line interface and tell NPM to download the package you want.
Command Prompt
Using a Package
var uc = require('upper-case’);
res.write(uc.upperCase("Hello World!"));
res.end();
}).listen(8080);
Creating user defined modules and fuctions
calj.js
calci.js
function add(a,b){
return a+b var calj = require('./calj');
}
exports.add = add result=calj.add(5,7)
console.log("The output is = "+result)
function sub(a,b){
return a-b result=calj.sub(7,5)
} console.log("The output is = "+result)
exports.sub = sub
Working with Node Packages
One of the most powerful features of the Node.js framework is the ability to easily extend it
with additional Node Packaged Modules (NPMs) using the Node Package Manager
(NPM).
A Node Packaged Module is a packaged library that can easily be shared, reused, and
installed in different projects.
Many different modules are available for a variety of purposes.
For example, the
Mongoose module provides an ODM (Operational Data Model) for MongoDB,
Express extends Node’s HTTP capabilities, and so on.
Node.js modules are created by various third-party organizations to provide the needed
features that Node.js lacks out of the box.
Node Packaged Modules include a package.json file that defines the packages.
The package.json file includes informational metadata, such as the name, version author,
and contributors, as well as control metadata, such as dependencies and other
requirements that the Node Package Manager uses when performing actions such as
installation and publishing.
The Node Package Manager allows you to find, install, remove, publish, and do everything
else related to Node Package Modules.
The Node Package Manager provides the link between the Node Package Registry and
your development environment.
npm command-line options (with express as the package, where appropriate)
Understanding the Node Package Registry
Command Prompt
Directives used in the package.json file
Directives used in the package.json file
• A great way to use package.json files is to automatically download and install the dependencies for
your Node.js app. All you need to do is create a package.json file in the root of your project code
and add the necessary dependencies to it. For example, the following package.
• json requires the express module as a dependency.
{
"name": "my_module",
"version": "0.1.0",
"dependencies" : {
"express" : "latest"
}
}
• Then you run the following command from root of your package, and the express module is
automatically installed.
• npm install
• Notice that no module is specified in the npm install.
• That is because npm looks for a package.json file by default.
• Later, as you need additional modules, all you need to do is add those to the dependencies
directive and then run npm install again.