Full Stack Notes Final
Full Stack Notes Final
Full Stack Notes Final
UNIT II NODE JS
Basics of Node JS – Installation – Working with Node packages – Using Node package
manager –Creating a simple Node.js application – Using Events – Listeners –Timers -
Callbacks – Handling Data I/O – Implementing HTTP services in Node.js
Basics of Node.JS
Node.js is a server-side platform built on Google Chrome's JavaScript Engine (V8
Engine).Node.js was developed by Ryan Dahl in 2009 and its latest version is v0.10.36.
Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and
scalable network applications.
Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and
efficient, perfect for data-intensive real-time applications that run across distributed
devices.
Node.js is an open source, cross-platform runtime environment for developing server-side
and networking applications. Node.js applications are written in JavaScript, and can be run
within the Node.js runtime on OS X, Microsoft Windows, and Linux.
Node.js also provides a rich library of various JavaScript modules which simplifies the
development of web applications using Node.js to a great extent.
Node.js = Runtime Environment + JavaScript Library
Features of Node.JS:
Following are some of the important features that make Node.js the first choice of software
architects.
1.Asynchronous and Event Driven –
All APIs of Node.js library are asynchronous,that is, non-blocking. It essentially means
a Node.js based server never waits foran API to return data.
The server moves to the next API after calling it and anotification mechanism of
Events of Node.js helps the server to get a response from the previous API call.
2.Very Fast
Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in
code execution.
Node.js can be used for a wide variety of purposes. Because it is based on V8 and has highly
optimized code to handle HTTP traffic, the most common use is as a webserver. However,
Node.js can also be used for a variety of other web services such as:
Installing Node.js
S.Yamunadevi AP/IT,PSNACET 2
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
To easily install Node.js, download an installer from the Node.js website at http://nodejs.org.
The Node.js installer installs the necessary files on your PC to get Node.js up and running. No
additional configuration is necessary to start creating Node.js applications.
The following list describes the executables in the Node.js install location that you need to get
started:
node: This file starts a Node.js JavaScript VM. If you pass in a JavaScript file location,
Node.js executes that script. If no target JavaScript file is specified,then a script prompt
is shown that allows you to execute JavaScript code directly from the console.
npm: This command is used to manage the Node.js packages
node_modules: This folder contains the installed Node.js packages. These packages
act as libraries that extend the capabilities of Node.js.
S.Yamunadevi AP/IT,PSNACET 3
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
The above code is enough to create an HTTP server which listens, i.e., waits for a request
over 8081 port on the local machine.
S.Yamunadevi AP/IT,PSNACET 4
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
REPL stands for Read Eval Print Loop and it represents a computer environment like a
Windows console or Unix/Linux shell where a command is entered and the system responds
with an output in an interactive mode. Node.js or Node comes bundled with a REPL
environment. It performs the following tasks:
Read - Reads user's input, parses the input into JavaScript data-structure, and stores in
memory.
Eval - Takes and evaluates the data structure.
Print - Prints the result.
Loop - Loops the above command until the user presses ctrl-c twice.
The REPL feature of Node is very useful in experimenting with Node.js codes and to debug
JavaScript codes.
REPL Commands
Using package.json
package.json is present in the root directory of any Node application/module and is
used to define the properties of a package. Let's open package.json of express package
present in node_modules/express/
{
"name": "express",
"description": "Fast, unopinionated, minimalist web framework",
"version": "4.11.2",
"author": {
"name": "TJ Holowaychuk",
"email": "[email protected]"
},
"contributors": [
{
"name": "Aaron Heckmann",
"email": "[email protected]"
},
{
"name": "Ciaran Jessup",
"email": "[email protected]"
},
{
"name": "Douglas Christopher Wilson",
"email": "[email protected]"
},
{
"name": "Guillermo Rauch",
"email": "[email protected]"
},
{
"name": "Jonathan Ong",
"email": "[email protected]"
},
Attributes of Package.json
S.Yamunadevi AP/IT,PSNACET 6
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
author - author of the package
contributors - name of the contributors to the package
dependencies - list of dependencies. NPM automatically installs all the dependencies
mentioned here in the node_module folder of the package.
repository - repository type and URL of the package
main - entry point of the package
keywords – keywords
Node.js is a single-threaded application, but it can support concurrency via the concept of
event and callbacks. Every API of Node.js is asynchronous and being single-threaded, they
use async function calls to maintain concurrency. Node uses observer pattern.
Node thread keeps an event loop and whenever a task gets completed, it fires the
corresponding event which signals the event-listener function to execute.
Event-Driven Programming
Node.js uses events heavily and it is also one of the reasons why Node.js is pretty fast
compared to other similar technologies. As soon as Node starts its server, it simply initiates its
variables, declares functions, and then simply waits for the event to occur.
In an event-driven application, there is generally a main loop that listens for events, and
then triggers a callback function when one of those events is detected
Although events look quite similar to callbacks, the difference lies in the fact that callback
S.Yamunadevi AP/IT,PSNACET 7
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
functions are called when an asynchronous function returns its result, whereas event handling
works on the observer pattern. The functions that listen to events act as Observers. Whenever
an event gets fired, its listener function starts executing.
Node.js has multiple in-built events available through events module and EventEmitter class
which are used to bind events and event-listeners as follows:
eventEmitter.emit('connection');
S.Yamunadevi AP/IT,PSNACET 8
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
console.log("Program Ended.");
Now let's try to run the above program and check its output:
$ mnode main.js
Output:
connection successful.
data received successfully.
Program Ended.
EVENTEMITTER CLASS
EventEmitter class lies in the events module. It is accessible via the following code:
When an EventEmitter instance faces any error, it emits an 'error' event. When a new
listener is added, 'newListener' event is fired and when a listener is removed,
'removeListener' event is fired.
EventEmitter provides multiple properties like on and emit. on property is used to bind a
function with the event and emit is used to fire an event.
EVENT METHODS
addListener(event, listener)
Adds a listener at the end of the listeners array for the specified event. No checks are
made to see if the listener has already been added.
Multiple calls passing the same combination of event and listener will result in the
listener being added multiple times. Returns emitter, so calls can be chained.
on(event, listener)
Adds a listener at the end of the listeners array for the specified event. No checks are
made to see if the listener has already been added.
S.Yamunadevi AP/IT,PSNACET 9
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
Multiple calls passing the same combination of event and listener will result in the
listener being added multiple times. Returns emitter, so calls can be chained.
once(event, listener)
Adds a one-time listener to the event. This listener is invoked only the next time the
event is fired, after which it is removed. Returns emitter, so calls can be chained
Node.js
removeListener(event, listener)
Removes a listener from the listener array for the specified event.
Caution: It changes the array indices in the listener array behind the listener.
removeListener will remove, at most, one instance of a listener from the listener array.
If any single listener has been added multiple times to the listener array for the
specified event, then removeListener must be called multiple times to remove each
instance. Returns emitter, so calls can be chained.
removeAllListeners([event])
Removes all listeners, or those of the specified event. It's not a good idea to remove
listeners that were added elsewhere in the code,
especially when it's on an emitter that you didn't create (e.g. sockets or file streams).
Returns emitter, so calls can be chained.
setMaxListeners(n)
By default, EventEmitters will print a warning if more than 10 listeners are added for a
particular event.
This is a useful default which helps finding memory leaks. Obviously not all Emitters
should be limited to 10.
This function allows that to be increased. Set to zero for unlimited.
listeners(event)
Returns an array of listeners for the specified event.
emit(event, [arg1], [arg2], [...])
Execute each of the listeners in order with the supplied arguments. Returns true if the
event had listeners, false otherwise.
Class Methods
listenerCount(emitter, event)
Returns the number of listeners for a given event Events
newListener
S.Yamunadevi AP/IT,PSNACET 10
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
event – String; the event name
listener – Function; the event handler function This event is emitted any time a listener
is added. When this event is triggered, the listener may not yet have been added to the
array of listeners for the event.
removeListener
event - String The event name
listener - Function The event handler function This event is emitted any time someone
removes a listener. When this event is triggered, the listener may not yet have been
removed from the array of listeners for the event.
Example: Creating a custom EventEmitter object and implementing three listeners that are
triggered when the balancedChanged event is triggered
Output:
C:\books\node\ch04>node emmiter_listener.js
Account balance: $220
Account balance: $540
Account balance: $1140
Goal Achieved!!!
Account balance: $-60
Account overdrawn!!!
TIMERS:
The timers module contains functions that can execute code after a certain period of time.You
do not need to import the timer module explicitly, as it is already globally available across the
emulated browser JavaScript API.
Scheduling Timers − This timer schedules the task to take place after a certain instant of time.
setImmediate()
setInterval()
setTimeout()
Cancelling Timers − This type of timers cancels the scheduled tasks which is set to take
place.
ClearImmediate()
clearInterval()
clearTimeout()
S.Yamunadevi AP/IT,PSNACET 12
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
Scheduling Timers
1. setTimeout() Method
The setTimeout() method schedules the code execution after a designated number of
milliseconds. Only after the timeout has occurred, the code will be executed. The specified
function will be executed only once. This method returns an ID that can be used in
clearTimeout() method.
setTimeout(function () {
// Will be printed after 2 seconds
return console.log(str);
}, 2000);
Output:
2. setImmediate() Method
setImmediate() executes the code at the end of the current event loop cycle.
Example
filename - immediate.js
Output
Simple statement in the event loop
setImmediate() function running
setTimeout() function running
3. setInterval() Method
setInterval() executes the code after the specified interval. The function is executed multiple
times after the interval has passed. The function will keep on calling until the process is
stopped externally or using code after specified time period.
Example
filename - interval.js
setInterval(function() {
console.log(‘Full stack- SIMPLY LEARNING');
}, 1000);
Output
4.clearImmediate() Method
This method clears the Immediate timer object that is created by the setImmediate() method.
Example
filename - clearImmediate.js
// clearImmediate() Example
S.Yamunadevi AP/IT,PSNACET 14
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
clearImmediate(timer);
console.log("Timer cancelled");
Output
Timer cancelled
5.clearInterval() Method
This method clears the Immediate timer object that is created by the setInterval() method.
Syntax
clearInterval(timer)
Example
filename - clearInterval.js
// clearInterval() Example
var si = setInterval(function A() {
return console.log("Setting Intevals for 500 ms !");
}, 500);
Output
6.clearTimeout() Method
This method clears the Immediate timer object that is created by the setTimeout() method.
Syntax
clearTimeout(timerObject)
Example
S.Yamunadevi AP/IT,PSNACET 15
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
filename - clearTimeout.js
// clearTimeout() Example
Output
CALLBACKS:
For example, a function to read a file may start reading a file and return the control to the
execution environment immediately so that the next instruction can be executed. Once file I/O
is complete, it will call the callback function while passing the callback function, the content
of the file as a parameter. So there is no blocking or wait for File I/O. This makes Node.js
highly scalable, as it can process a high number of requests without waiting for any function
to return results.
Blocking Code Example
Full stack web development is the new era of the technological world. It makes the websites
more interactive and user friendly!!!!!
S.Yamunadevi AP/IT,PSNACET 16
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
var fs = require("fs");
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program Ended");
Output
Full stack web development is the new era of the technological world. It makes the websites
more interactive and user friendly!!!!!
Program Ended
Full stack web development is the new era of the technological world. It makes the websites
more interactive and user friendly!!!!!
var fs = require("fs");
fs.readFile('input.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("Program Ended");
Output
Program Ended
Full stack web development is the new era of the technological world. It makes the websites
more interactive and user friendly!!!!!
These two examples explain the concept of blocking and non-blocking calls.
S.Yamunadevi AP/IT,PSNACET 17
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
The first example shows that the program blocks until it reads the file and then only it
proceeds to end the program.
The second example shows that the program does not wait for file reading and
proceeds to print "Program Ended" and at the same time, the program without blocking
continues reading the file.
Thus, a blocking program executes very much in sequence.
From the programming point of view, it is easier to implement the logic but non-
blocking programs do not execute in sequence.
In case a program needs to use any data to be processed, it should be kept within the
same block to make it sequential execution.
Definition of JSON:
One of the most common data types that you work with when implementing Node.js
web applications and services is JSON (JavaScript Object Notation).
JSON is a lightweight method to convert JavaScript objects into a string form and then
back again.
This provides an easy method when you need to serialize data objects when passing
them from client to server, process to process, stream to stream, or when storing them
in a database.
There are several reasons to use JSON to serialize your JavaScript objects over XML
including the following:
JSON is much more efficient and takes up fewer characters.
Serializing/deserializing JSON is faster than XML because it’s simpler syntax.
JSON is easier to read from a developer’s perspective because it is similar to
JavaScript syntax.
The only reasons you might want to use XML over JSON are for complex objects or if
you have XML/XSLT transforms already in place.
Node also allows you to convert a JavaScript object into a properly formatted JSON string.
Thus the string form can be stored in a file or database, sent across an HTTP connection, or
written to a stream/buffer. Use the JSON.stringify(text) method to parse JSON text and
generate a JavaScript object
BUFFERS:
S.Yamunadevi AP/IT,PSNACET 18
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
Buffer class is a global class that can be accessed in an application without importing the
buffer module.
Creating Buffers
Though "utf8" is the default encoding, you can use any of the following encodings "ascii",
"utf8", "utf16le", "ucs2", "base64" or "hex".
Writing to Buffers
Syntax
Following is the syntax of the method to write into a Node Buffer:
buf.write(string[, offset][, length][, encoding])
Parameters
Here is the description of the parameters used:
string - This is the string data to be written to buffer.
offset - This is the index of the buffer to start writing at. Default value is 0.
length - This is the number of bytes to write. Defaults to buffer.length.
encoding - Encoding to use. 'utf8' is the default encoding.
S.Yamunadevi AP/IT,PSNACET 19
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
Return Value
This method returns the number of octets written. If there is not enough space in the
buffer to fit the entire string, it will write a part of the string.
Example
buf = new Buffer(256);
len = buf.write("Simply Easy Learning");
console.log("Octets written : "+ len);
Output:
abcdefghijklmnopqrstuvwxyz
abcde
abcde
abcde
Convert Buffer to JSON
Syntax
Following is the syntax of the method to convert a Node Buffer into JSON object:
buf.toJSON()
Return Value
This method returns a JSON-representation of the Buffer instance.
Example
var buf = new Buffer('Simply Easy Learning');
var json = buf.toJSON(buf);
console.log(json);
S.Yamunadevi AP/IT,PSNACET 21
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
Output:
[ 83, 105, 109, 112, 108, 121, 32, 69, 97, 115, 121, 32, 76, 101, 97, 114, 110,105, 110, 103 ]
Concatenate Buffers
Syntax
Following is the syntax of the method to concatenate Node buffers to a single Node Buffer:
Buffer.concat(list[, totalLength])
Parameters
Here is the description of the parameters used:
list - Array List of Buffer objects to be concatenated.
totalLength - This is the total length of the buffers when concatenated.
Return Value
This method returns a Buffer instance.
Example
var buffer1 = new Buffer('Happy ');
var buffer2 = new Buffer('Learning');
var buffer3 = Buffer.concat([buffer1,buffer2]);
console.log("buffer3 content: " + buffer3.toString());
Output:
buffer3 content: Happy Learning
Buffer Length
Syntax
buf.length;
Return Value
Returns the size of a buffer in bytes.
S.Yamunadevi AP/IT,PSNACET 22
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
Example
var buffer = new Buffer('PSNACETIT');
//length of the buffer
console.log("buffer length: " + buffer.length);
Output:
buffer length: 10
STREAMS
Streams are objects that let you read data from a source or write data to a destination in
continuous fashion. In Node.js, there are four types of streams:
Readable - Stream which is used for read operation.
Writable - Stream which is used for write operation.
Duplex - Stream which can be used for both read and write operation.
Transform - A type of duplex stream where the output is computed based on input.
Each type of Stream is an EventEmitter instance and throws several events at different
instance of times. For example, some of the commonly used events are:
data - This event is fired when there is data is available to read.
end - This event is fired when there is no more data to read.
error - This event is fired when there is any error receiving or writing data.
finish - This event is fired when all the data has been flushed to underlying system.
Reading from a Stream
Create a text file named input.txt having the following content:
Full stack web development is the process of creating, testing and deploying the web
applications!!
Create a js file named main.js with the following code:
var fs = require("fs");
var data = '';
// Create a readable stream
var readerStream = fs.createReadStream('input.txt');
// Set the encoding to be utf8.
S.Yamunadevi AP/IT,PSNACET 23
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
readerStream.setEncoding('UTF8');
// Handle stream events --> data, end, and error
readerStream.on('data', function(chunk) {
data += chunk;
});
readerStream.on('end',function(){
console.log(data);
});
readerStream.on('error', function(err){
console.log(err.stack);
});
console.log("Program Ended");
Output
Program Ended
Full stack web development is the process of creating, testing and deploying the web
applications!!
Writing to a Stream
Create a js file named main.js with the following code:
var fs = require("fs");
var data = 'Simply Easy Learning';
// Create a writable stream
var writerStream = fs.createWriteStream('output.txt');
// Write the data to stream with encoding to be utf8
writerStream.write(data,'UTF8');
// Mark the end of file
writerStream.end();
// Handle stream events --> finish, and error
writerStream.on('finish', function() {
console.log("Write completed.");
});
S.Yamunadevi AP/IT,PSNACET 24
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
writerStream.on('error', function(err){
console.log(err.stack);
});
console.log("Program Ended");
Output
Program Ended
Write completed.
Now open output.txt created in your current directory; it should contain the following:
Simply Easy Learning
Piping the Streams
Piping is a mechanism where we provide the output of one stream as the input to
another stream.
It is normally used to get data from one stream and to pass the output of that stream to
another stream.
There is no limit on piping operations. Now we'll show a piping example for reading
from one file and writing it to another file.
Output.
Program Ended
Open output.txt created in your current directory; it should contain the following:
S.Yamunadevi AP/IT,PSNACET 25
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
Full stack web development is the process of creating, testing and deploying the web
applications!!
http.ClientRequest object:
The ClientRequest object is created internally when you call http.request() when
building the HTTP client.
This object represents the request while it is in progress to the server. You use the
ClientRequest object to initiate, monitor, and handle the response from the server.
The ClientRequest implements a Writable stream, so it provides all the functionality of
a Writable stream object.
For example, you can use the write() method to write to it as well as pipe a Readable
stream into it.
http.ServerResponse Object
The ServerResponse object is created by the HTTP server internally when a request
event is received.
It is passed to the request event handler as the second argument. You use the
ServerRequest object to formulate and send a response to the client.
The ServerResponse implements a Writable stream, so it provides all the functionality
of a Writable stream object.
For example, you can use the write() method to write to it as well as pipe a Readable
stream into it to write data back to the client.
http.IncomingMessage Object
The IncomingMessage object is created either by the HTTP server or the HTTP client.
On the server side, the client request is represented by an IncomingMessage object,
and on the client side the server response is represented by an IncomingMessage
object.
The IncomingMessage object can be used for both because the functionality is
basically the same.
S.Yamunadevi AP/IT,PSNACET 26
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
The IncomingMessage implements a Readable stream, allowing you to read the client
request or server response as a streaming source.
This means that the readable and data events can be listened to and used to read data
from the stream.
http.Server Object
The Node.js HTTP Server object provides the fundamental framework to implement
HTTP servers.
It provides an underlying socket that listens on a port and handles receiving requests
and then sends responses out to client connections.
While the server is listening, the Node.js application will not end.
Example:Implementing an HTTP web service that connects remotely to an external source for
weather data
var options = {
host: 'api.openweathermap.org',
path: '/data/2.5/weather?q=' + city + '&APPID=' + APIKEY
};
http.request(options, function(weatherResponse){
parseWeather(weatherResponse, res);
}).end();
}
http.createServer(function (req, res) {
console.log(req.method);
if (req.method == "POST"){
var reqData = '';
req.on('data', function (chunk) {
reqData += chunk;
});
req.on('end', function() {
var postParams = qstring.parse(reqData);
getWeather(postParams.city, res);
});
} else {
sendResponse(null, res);
}
}).listen(8080);
OUTPUT:
S.Yamunadevi AP/IT,PSNACET 28
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
S.Yamunadevi AP/IT,PSNACET 29
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
Understanding NoSQL and MongoDB – Building MongoDB Environment – User accounts – Access
control – Administering databases – Managing collections – Connecting to MongoDB from Node.js –
simple applications
MongoDB:
MongoDB is a cross-platform, document oriented database that provides, high performance, high
availability, and easy scalability. MongoDB works on concept of collection and document.
Database
Database is a physical container for collections. Each database gets its own set of files on the file
system. A single MongoDB server typically has multiple databases.
Document
A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema means that
documents in the same collection do not need to have the same set of fields or structure, and common
fields in a collection's documents may hold different types of data.
The following table shows the relationship of RDBMS terminology with MongoDB.
Schema less: MongoDB is a document database in which one collection holds different
documents. Number of fields, content and size of the document can differ from one document to
another.
Structure of a single object is clear.
No complex joins.
Deep query-ability. MongoDB supports dynamic queries on documents using a document-based
query language that's nearly as powerful as SQL.
Ease of scale-out: MongoDB is easy to scale.
Conversion/mapping of application objects to database objects not needed.
Document Oriented Storage: Data is stored in the form of JSON style documents.
Index on any attribute
Replication and high availability
Auto-sharding
Rich queries
Fast in-place updates
Professional support by MongoDB
Applications of MongoDB
Big Data
Content Management and Delivery
Mobile and Social Infrastructure
User Data Management
depending upon your Windows version. To get your Windows version, open command prompt and
execute the following command.
S.Yamunadevi AP/IT,PSNACET
2
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
32-bit versions of MongoDB only support databases smaller than 2GB and suitable only for testing and
evaluation purposes.
Now extract your downloaded file to c:\ drive or any other location. Make sure the name of the extracted
folder is mongodb-win32-i386-[version] or mongodb-win32-x86_64-[version].
Next, open the command prompt and run the following command.
In case you have extracted the MongoDB at different location, then go to that path by using command
cd FOOLDER/DIR and now run the above given process.
MongoDB requires a data folder to store its files. The default location for the MongoDB data directory
is c:\data\db.
So you need to create this folder using the Command Prompt. Execute the following command
sequence.
C:\>md data
C:\md data\db
If you have to install the MongoDB at a different location, then you need to specify an alternate path for
\data\db by setting the path dbpath in mongod.exe.
For the same, issue the following commands.
In the command prompt, navigate to the bin directory present in the MongoDB installation folder.
Suppose my installation folder is D:\set up\mongodb
C:\Users\XYZ>d:
D:\>cd "set up"
D:\set up>cd mongodb
D:\set up\mongodb>cd bin
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"
This will show waiting for connections message on the console output, which indicates that the
mongod.exe process is running successfully.
Now to run the MongoDB, you need to open another command prompt and issue the following
command.
D:\set up\mongodb\bin>mongo.exe
MongoDB shell version: 2.4.6
S.Yamunadevi AP/IT,PSNACET
3
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
This will show that MongoDB is installed and run successfully. Next time when you run MongoDB,
you need to issue only commands.
Start MongoDB
sudo service mongodb start
Stop MongoDB
sudo service mongodb stop
Restart MongoDB
sudo service mongodb restart
Syntax
Basic syntax of use DATABASE statement is as follows:
use DATABASE_NAME
Example
If you want to create a database with name <mydb>, then use DATABASE statement would be as
follows:
>use mydb
S.Yamunadevi AP/IT,PSNACET
4
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
switched to db mydb
To check your currently selected database, use the command db
>db mydb
If you want to check your databases list, use the command show dbs.
>show dbs
local 0.78125GB
test 0.23012GB
Your created database (mydb) is not present in list. To display database, you need to insert at least one
document into it.
>db.movie.insert({"name":"sample_db"})
>show dbs
local 0.78125GB
mydb 0.23012GBtest 0.23012GB
In MongoDB default database is test. If you didn't create any database, then collections will be stored in
test database
The dropDatabase() Method
MongoDB db.dropDatabase() command is used to drop a existing database.
Syntax
Basic syntax of dropDatabase() command is as follows:
db.dropDatabase()
This will delete the selected database. If you have not selected any database, then it will delete default
'test' database.
Example
First, check the list of available databases by using the command, show dbs.
>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
>
If you want to delete new database <mydb>, then dropDatabase() command would be as follows:
>use mydb
switched to db mydb
>db.dropDatabase()
>{ "dropped" : "mydb", "ok" : 1 }
>
S.Yamunadevi AP/IT,PSNACET
5
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
>show dbs
local 0.78125GB
test 0.23012GB>
─ Drop Database
The MongoDB shell provides several commands that can be executed from the shell prompt.
help <option>: Displays syntax help for MongoDB shell commands. The option argument allows you
to specify an area where you want help.
use <database>: Changes the current database handle. Database operations are processed on the current
database handle.
profile: Displays the five most recent system.profile entries taking more than 1 millisecond.
roles: Displays a list of all roles for the current database, both built-in and user-defined.
load(script): Loads and runs a JavaScript file inside the shell. This is a great way to script operations
for the database.
S.Yamunadevi AP/IT,PSNACET
6
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
USER ACCOUNTS:
MongoDB provides the ability to add, remove, and configure users from the MongoDB shell
Listing Users
User accounts are stored in the db.system.users collection of each database. The user object contains
_id, user, pwd, roles, and sometimes other DB Roles fields. The following commands show changing to
the admin database and listing users, as shown in Figure.
use admin
show users
You can also use a query such as find on the db.system.users collection. The difference is that
db.system.users.find() returns a cursor object that you can use to access the User documents.
For example, the following code gets a cursor for users in the admin database and returns the count of
users:
use admin
cur = db.system.users.find()
cur.count()
You can use the MongoDB shell to create user accounts that can administer, read,and write to the
databases. User accounts are added using the createUser() method inside the MongoDB shell.
S.Yamunadevi AP/IT,PSNACET
7
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
The createUser() method accepts a document object that allows you to specify the username, roles, and
password that apply to that user.
Role Description
read Allows the user to read data from any collection within the
database.
Example:
use test
db.createUser( { user: "testUser",
pwd: "test",
roles: [ "readWrite", "dbAdmin" ] } )
Removing Users
Synatax: removeUser(<username>)method.
Example
use testDB
db.removeUser("testUser")
S.Yamunadevi AP/IT,PSNACET
8
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
ADMINISTERING DATABASES:
The core administration documents address strategies and practices used in the operation of MongoDB
systems and deployments.
Operational Strategies –Higher level documentation of key concepts for the operation and
maintenance of MongoDB deployments.
MongoDB Backup Methods – Describes approaches and considerations for backing up a MongoDB
database.
Monitoring for MongoDB – An overview of monitoring tools, diagnostic strategies, and approaches to
monitoring replica sets and sharded clusters.
Data Management – Core documentation that addresses issues in data management, organization,
maintenance, and lifecycle management.
Data Center Awareness – Presents the MongoDB features that allow application developers and
database administrators to configure their deployments to be more data center aware or allow
operational and location-based separation.
Capped Collections – Capped collections provide a special type of size-constrained collections that
preserve insertion order and can support high volume inserts.
MANAGING COLLECTION:
S.Yamunadevi AP/IT,PSNACET
9
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
Need not define column and data type while creating a collection.
Collection name starts with name or namespace, and it can have any numbers.
The collection name should not exceed 128 characters.
By using (.), the collection gets organized into groups.
We can create any number of collections in the database.
First create a database to store the collection value.
USE<"database name">
create.collection_name (<document>)
use hospital
Collection-1
db.create patient()
db.patient.insert({name:'akash',age:23,reason:'fever'})
db.patient.insert(
{name:'megha',age:24,reason:'fever'},
{name:'rohit',age:25,reason:'cuff'}
Collection-2
db.patienthistory.insert({name:'rupali',age:34,
experience:12})
Delete a collection
db.patienthistory.drop()
show collections
S.Yamunadevi AP/IT,PSNACET
10
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
Using a MongoClient object to connect to MongoDB involves creating an instance of the client, opening
a connection to the database, authenticating to the database if necessary, and then handling logout and
closure as needed.
To connect to MongoDB via a MongoClient object, first create an instance of the MongoClient object
using the following syntax:
var client = new MongoClient();
After you have created the MongoClient, you still need to open a connection to the MongoDB server
database using the connect(url, options,callback) method
mongodb://[username:password@]host[:port][/[database][?options]]
For example, to connect to a MongoDB database named MyDB on a host named MyDBServer on port
8088, you would use the following URL:
client.connect('mongodb://MyDBServer:8088/MyDB');
MongoClient connection url components
Option Description
mongodb :// Specifies that this string is using a MongoDB connection
format
username (Optional) Specifies the user name to use when authenticating.
password (Optional) Specifies the password to use when authenticating.
host Specifies the host name or address of the MongoDB server. You
can specify multiple host:port combinations to connect to
multiple MongoDB servers by separating them by a comma. For
example: mongodb://host1:270017,host2:27017,host3:2
port Specifies the port to use when connecting to the MongoDB
server. Default is 27017.
database Specifies the database name to connect to. Default is admin.
options Specifies the key/value pairs of options to use when
connecting. These same options can be specified in the dbOpt
and serverOpt
For example, the following code shows connecting to MongoDB with a reconnect interval of 500 and a
connection timeout of 1000 milliseconds:
client.connect ('mongodb://MyDBServer:8088/MyDB',
{ connectTimeoutMS: 1000,
reconnectInterval: 500 },
S.Yamunadevi AP/IT,PSNACET
11
IT3501 FULL STCK WEB DEVELOPMENT PSNACET/IT
S.Yamunadevi AP/IT,PSNACET
12
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
UNIT IV
Implementing Express in Node.js - Configuring routes - Using Request and Response objects -
Angular - Typescript - Angular Components - Expressions - Data binding - Built-in directives
It is simple to start using Express in your Node.js projects. All you need to do is add the express
module using the following command from the root of your project:
npm install express
You can also add express to your package.json module to ensure that express is installed when you
deploy your application. Once you have installed express, you need to create an instance of the express
class to act as the HTTP server for your Node.js application. The following lines of code import the
express module and create an instance of express that you can use:
var express = require('express');
var app = express();
Starting the Express Server To begin implementing Express as the HTTP server for your Node.js
application, you need to create an instance and begin listening on a port. The following three lines of
code start a rudimentary Express server listening on port 8080:
var express = require('express');
var app = express(); app.listen(8080);
A route is simply a definition that describes how to handle the path portion of the URI in the HTTP
request to the Express server.
There are two parts when defining the route. First is the HTTP request method (typically GET or
POST). The express module provides a series of functions that allow you to implement routes for the
Express server. These functions all use the following syntax:
S.YAMUNADEVI AP/IT 1
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
S.YAMUNADEVI AP/IT 2
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
Request Objects
The route handlers are passed a Request object as the first parameter. The Request object provides the
data and metadata about the request, including the URL, headers, query string, and much more
S.YAMUNADEVI AP/IT 3
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
Response objects
The Response object passed to the route handler provides the necessary functionality to build and send
a proper HTTP response.The most commonly used methods are get(header) and set(header, value),
which gets and sets any header value.
S.YAMUNADEVI AP/IT 4
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
Sending status, headers, and response data using the Response object
var express = require('express');
var url = require('url');
var app = express();
app.listen(80);
app.get('/', function (req, res) {
var response = '<html><head><title>Simple Send</title></head>' +'<body><h1>Hello from
Express</h1></body></html>';
res.status(200);
res.set({'Content-Type': 'text/html', 'Content-Length': response.length});
res.send(response);
console.log('Response Finished? ' + res.finished);
console.log('\nHeaders Sent: ');
console.log(res.headerSent);
});
app.get('/error', function (req, res) {
res.status(400);
res.send("This is a bad request.");
});
S.YAMUNADEVI AP/IT 5
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
ANGULAR:
Angular is a javascript framework for building single-page client applications using HTML and
TypeScript.
Angular is written in TypeScript, supported and developed by Google.
Framework:
Framework is platform for developing a software applications
Framework can have in build classes and functions that provides APIs for performing
operations
It can be reused to add several functionalities
Single page Application:
A single page application is a website or web application that dynamically rewrites a current
web page with new data
It doesn‟t require for a web browser loading entire new pages.
Examples like Gmail, Google Maps, Netflix etc.
Features of an angular:
1. Document Object Model
DOM (Document Object Model) treats an XML or HTML document as a tree structure in which each
node represents a part of the document.
Angular uses regular DOM. Consider that ten updates are made on the same HTML page. Instead of
updating the ones that were already updated, Angular will update the entire tree structure of HTML
tags.
2. TypeScript
TypeScript defines a set of types to JavaScript, which helps users write JavaScript code that is
easier to understand.
All of the TypeScript code compiles with JavaScript and can run smoothly on any platform.
S.YAMUNADEVI AP/IT 6
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
Angular Architecture:
Angular is a full-fledged model-view-controller (MVC) framework. It provides clear guidance on how
the application should be structured and offers bi-directional data flow while providing real DOM.
1.Modules
An Angular app has a root module, named AppModule, which provides the bootstrap
mechanism to launch the application.
2. Components
Each component in the application defines a class that holds the application logic and data. A
component generally defines a part of the user interface (UI).
3. Templates
The Angular template combines the Angular markup with HTML to modify HTML elements before
they are displayed. There are two types of data binding:
S.YAMUNADEVI AP/IT 7
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
Event binding: Lets your app respond to user input in the target environment by updating your
application data.
Property binding: Enables users to interpolate values that are computed from your application data into
the HTML.
4. Metadata
Metadata tells Angular how to process a class. It is used to decorate the class so that it can configure
the expected behavior of a class.
5. Services
When you have data or logic that isn‟t associated with the view but has to be shared across
components, a service class is created. The class is always associated with the @Injectible decorator.
6. Dependency Injection
This feature lets you keep your component classes crisp and efficient. It does not fetch data from a
server, validate the user input, or log directly to the console. Instead, it delegates such tasks to the
services.
TYPESCRIPT:
TypeScript
Typescript is an open-source object-oriented programing language.
It is a superset of JavaScript
It contains all elements of the JavaScript.
It is a language designed for large-scale JavaScript application development, which can be
executed on any browser, any Host, and any Operating System.
The TypeScript is a language as well as a set of tools.
Typescript components
Fields: It is a variable declared in a class.
Methods: It represents an action for the object.
Constructors: It is responsible for initializing the object in memory.
Nested class and interface: It means a class can contain another class.
Data Types in Typescript:
TypeScript uses data types to handle data, but there are some differences in syntax. TypeScript also
adds in an extra type enumeration. The following list goes over the types and variables and their syntax
for TypeScript:
String:
This data type stores character data as a string.
The character data is specified by either single or double quotation marks.
All the data contained in the quotes will be assigned to the string variable.
S.YAMUNADEVI AP/IT 8
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
S.YAMUNADEVI AP/IT 9
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
S.YAMUNADEVI AP/IT 10
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
Styles: This option allows you to add inline CSS to your component. Use it when only minor style
changes are needed.
StylesUrls: This option allows you to import an array of external CSS
Stylesheet(s). You should use this rather than styles when importing external CSS files.
ViewProviders: This is an array of dependency injection providers. It allows you to import and use
Angular services that provide application functionality such as HTTP communications.
Example:1 A Simple Angular Template and Styling to Display a <span> Element
import { Component } from '@angular/core';@Component
({
selector: 'app-root',
template: `
<span>Hello my name is Brendan</span>`,
styles:[`span {
font-weight: bold;
border: 1px ridge blue;
padding: 5px;} `]
})
export class AppComponent {
title = 'Chapter 22 Intro';
}
Output:
Example 2 :The following example shows that sample table using Angular component.
Component.ts:
import { Component } from "@angular/core"; @Component({
selector: „Example-1',
templateUrl: 'app/app.component.html'
S.YAMUNADEVI AP/IT 11
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
})
export class AppComponent {
name: string = "Karthik"
}
App.component.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<h1>This is {{name}} Home Page</h1>
</body>
</html>
Output:
styles: [` span{
S.YAMUNADEVI AP/IT 12
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
Example-4 A Component that Takes Data through Its Selector to Modify What Is Displayed via
HTML
import {Component, Input} from '@angular/core';
@Component ({
selector: "myInput",
template: `
<div>
Name: {{personName}}
<br />
Job: {{occupation}}
</div>`,
styles: [` div {
margin: 10px;
padding: 15px;
border: 3px solid grey;} `]
})
export class myInputs {
@Input('name') personName: string;
@Input('occupation') occupation: string;
constructor() {
this.personName = "John Doe";
this.occupation = "Anonymity"
}}
Output:
S.YAMUNADEVI AP/IT 13
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
EXPRESSIONS:
Using expressions is the simplest way to represent data from a component in an Angular view.
Expressions are encapsulated blocks of code inside brackets, like this:
{{expression}}
The Angular compiler compiles an expression into HTML elements so that theresults of the expression
are displayed. For example, look at the following expressions:
{{1+5}}
{{'One' + 'Two'}}
Based on these expressions, the web page displays the following values:
6
OneTwo
Direct declaration of the name and score values in the template expressions, as shown here:
Name: {{name}}
Score: {{score}}
Adjusted: {{score+5}}
Angular expressions are similar to TypeScript/JavaScript expressions in several ways, but they differ
in these ways:
Attribute evaluation: Property names are evaluated against the component model instead of against
the global JavaScript namespace.
More forgiving: Expressions do not throw exceptions when they encounter undefined or null variable
types; instead, they treat them as having no value.
No flow control: Expressions do not allow the following:
Assignments (for example, =, +=, -=)
The new operator
Conditionals
Loops
Increment and decrement operators (++ and --)
Also, you cannot throw an error inside an expression
Example: Basic Strings and Numbers with Simple Math Operations in an Angular Template
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<h1>Expressions</h1>
Number:<br>
{{5}}<hr>
String:<br>
S.YAMUNADEVI AP/IT 14
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
{{'My String'}}<hr>
Adding two strings together:<br>
{{'String1' + ' ' + 'String2'}}<hr>
Adding two numbers together:<br>
{{5+5}}<hr>
Adding strings and numbers together:<br>
{{5 + '+' + 5 + '='}}{{5+5}}<hr>
Comparing two numbers with each other:<br>
{{5= = 5 }}<hr>‟
})
Export class App component{}
Output:
DATA BINDING:
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.
Angular provides a very clean interface to link the model data to elements in a web page.
There are many ways in Angular to use data binding to make an application look andact in different
ways.
Interpolation: You can use double curly braces ({{}}) to get values directly from the
Component class.
Property binding: You can use this type of binding to set the property of an HTML element.
Event binding: You can use this type of binding to handle user inputs.
Attribute binding: This type of binding allows the setting of attributes to an HTML element.
Class binding: You can use this type of binding to set CSS class names to the element.
Style binding: You can use this type of binding to create inline CSS styles for the element.
S.YAMUNADEVI AP/IT 15
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
Two-way binding with ngModel: You can use this type of binding with data entry forms to
receive and display data.
String Interpolation:
Interpolation involves using the {{}} double curly braces to evaluate a template expression. This can
be in a hard-coded form, or it can reference a property of the Component class.
Example:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
{{str1 + ' ' + name}}
<br>
<img src="{{imageSrc}}" />
<br>
<p>{{str2 + getLikes(likes)}}</p>`,
styles: [`
img{
width: 300px;
height: auto;
}
p{
font-size: 35px;
color: darkBlue;
} `]
})
export class AppComponent {
str1: string = "Hello my name is"
name: string = "Brendan"
str2: string = "I like to"
likes: string[] = ['hike', "rappel", "Jeep"]
getLikes = function(arr: any){
var arrString = arr.join(", ");
return " " + arrString
}
imageSrc: string = "../assets/images/angelsLanding.jpg"}
Output:
S.YAMUNADEVI AP/IT 16
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
Property Binding
Property binding in Angular helps you set values for properties of HTML elements or directives. Use
property binding to do things such as toggle button features, set paths programmatically, and share
values between components.
Example:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<img [src]="myPic"/>
<br>
<button [disabled]="isEnabled">Click me</button><hr>
<button disabled="{!isEnabled}">Click me</button><br>
<p [ngClass]="className">This is cool stuff</p> `,
styles: [`
img {
height: 100px;
width auto;}
.myClass {
color: red;
font-size: 24px;
}
`]
})
export class AppComponent {
myPic: string = "../assets/images/sunset.JPG";
isEnabled: boolean = false;
className: string = "myClass";
}
Output:
Event Binding:
Event binding lets you listen for and respond to user actions such as keystrokes, mouse movements,
clicks, and touches.
S.YAMUNADEVI AP/IT 17
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
Example:
Event Binding to Change the Image URL That Displays on the Web Page
S.YAMUNADEVI AP/IT 18
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
changeImg = function(){
if(this.counter < this.imageArray.length - 1){
this.counter++;
}else{ this.counter = 0;
}
this.imageUrl=this.imageArray[this.counter]; }
onKeyup(event:any){
this.upValues = event.key;
this.upValues += event.target.value + ' | ';
}
onKeydown(event:any){
this.downValues = event.key;
this.downValues += event.target.value + " | ";
}
keypress(event:any){
this.keypressValue = event.key;
this.keypressValue += event.target.value + " | ";
}
move(event:any){
this.x = event.clientX;
this.y = event.clientY; }
underTheScope(event:any){
if(event.type == "focus"){
this.view = "the text box is focused";
}
else if(event.type == "blur"){
this.view = "the input box is blurred";
}
}
Console.log(event)
}};
Output:
S.YAMUNADEVI AP/IT 19
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
Two-Way Binding
Two-way binding allows for data to be easily displayed and updated simultaneously. This makes it
easy to reflect any changes the user makes to the DOM. Angular does this by using ngModel to watch
for changes and then update the value.
syntax:
<input [(ngModel)] = "myValue">
Example:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<input [(ngModel)]="text"><br>
<input bindon-ngModel="text"><br>
<input [value]="text" (input)="text=$event.target.value">
<h1>{{text}}</h1>
`
})
export class AppComponent {
text: string = "some text here";
}
Class Binding
Class binding is used to bind CSS style tags to HTML elements. It assigns the class based on the
result of an expression being true or false. If the result is true, the class gets assigned.
Syntax:
Example:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<div [class]="myCustomClass"></div>
<span [class.redText]="isTrue">Hello my blue friend</span> `,
styles: [`
.blueBox {
height: 150px;
width: 150px;
background-color: blue;
}
.redText{
color: red; font-size: 24px;
}`]
})
S.YAMUNADEVI AP/IT 20
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
BUILT-IN DIRECTIVES
Directives are a combination of Angular template markup and supporting TypeScript code.
Angular directive markups can be HTML attributes, element names, or CSS classes.
The TypeScript directive code defines the template data and behavior of the HTML elements.
The Angular compiler traverses the template DOM and compiles all directives.
Then it links the directives by combining a directive with a scope to produce a new live view.
The live view contains the DOM elements and functionality defined in the directive.
The following sections describe most of the Angular directives, which fall into three categories:
Component: A directive with a template
Structural: A directive that manipulates elements in the DOM
Attribute: A directive that manipulates the appearance and behavior of a DOM element
Components Directives
Angular components are a form of structural directive that utilize a template. A component creates a
selector that is used as an HTML tag to dynamically add HTML, CSS, and Angular logic to the DOM.
Components are at the heart of Angular.
Structural Directives
Several directives dynamically update, create, and remove elements from the DOM. These directives
create the layout, look, and feel of an application.
Attribute Directives
Angular attribute directives modify how HTML elements look and behave. They are injected straight
into the HTML and dynamically modify how the user interacts with an HTML segment. Attribute
directives are so named because they often look like normal HTML attributes.
ngModel This directive watches a variable for changes and then updates
display values based on those changes. Consider these examples:
<input [(ngModel)]="text"><br>
<h1>{{text}}</h1>
ngForm This directive creates a form group and allows it to track the
values and validation within that form group. By using ngSubmit,
you can pass the form data as an object to the submission event.
S.YAMUNADEVI AP/IT 21
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
App.Component.ts
if (opt.selected){
this.selectedClass.push(opt.text);
}
}
}
}
Attribute.component.html
<form>
<span>name: </span>
<input name="name" [(ngModel)]="name">
<br>
<span>color:</span>
<input type="checkbox" (click)="enabler()">
<select #optionColor [(ngModel)]="color" name="color"
[disabled]="isDisabled">
<option *ngFor="let color of colors" [value]="color">
{{color}}
</option>
</select><hr>
<span>Change Class</span><br>
<select #classOption multiple name="styles" (change)="addClass($event)">
<option *ngFor="let class of classes" [value]="class" >
{{class}}
</option>
</select><br>
<span>press and hold control/command
<br>to select multiple options
S.YAMUNADEVI AP/IT 22
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
</span>
</form>
<hr>
<span>Name: {{name}}</span><br>
<span [ngClass]="selectedClass"
[ngStyle]="{'color': optionColor.value}">
color: {{optionColor.value}}
</span><br>
Attribute.component.css
.bold {
font-weight: bold;
}
.italic {
font-style: italic;
}
.highlight {
background-color: lightblue;
}
Output:
S.YAMUNADEVI AP/IT 23
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
UNIT V REACT
MERN STACK – Basic React applications – React Components – React State – Express RESTAPIs –
Modularization and Webpack – Routing with React Router – Server-side rendering
MERN STACK:
MERN Stack is a collection of powerful technologies and robust, used to develop scalable master web
applications comprising backend, front-end, and database components. It is JavaScript that is used
for the faster and easier development of full-stack web applications. MERN Stack is a technology that
is a user-friendly full-stack JavaScript framework for building applications and dynamic websites.
MERN Stack consists of four main components or can say four main technologies:
1. M stands for MongoDB ( Database ), mainly used for preparing document database and is a
NoSQL (Non-Structured Query Language ) Database System
2. E stands for Express, mainly used for developing Node.js web framework
3. R stands for React, mainly used for developing a client-side JavaScript framework
4. N stands for js, mainly used for developing the premier JavaScript web server
Each of these four technologies plays an important role in providing an end-to-end framework for the
developers. Even these four technologies play an important role in the development process of web
applications.
Reason to choose MERN Stack for building Mobile and Web applications:
1. Cost-effective:All the four technologies that are mentioned above, MERN (MongoDB,
Express.js, React.js, and Node.js) are used in MERN Stack is built on JavaScript that makes it
cost-effective and within less cost investment user will able to get the better results or output.
2. SEO friendly:Here, SEO (Search Engine Optimization) friendly means that Google, Yahoo
and other search engines can search each page on the website efficiently and easily, interpret
and correlate the content effectively with the searched text and easily index it in their database.
As whenever websites are created using MERN technologies, then it is always SEO friendly.
3. Better performance:Better performance refers to the faster response between backend and
front-end and database, which ultimately improves the website speed and yields better
performance, thus providing a smooth user experience.
4. Improves Security: It mainly concerns the security of applications generated using MERN;
her web application security refers to various processes, methods or technologies used for
protecting web servers and various web applications, such as APIs (Application user
S.YAMUNADEVI AP/IT 1
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
interface) from the attack by internet-based threats. Generally, secured hosting providers can
easily integrate applications created using the MERN stack. For more or better security Mongo
DB and Node.js security tools are also used.
5. Provide the fastest delivery:Any Web applications and mobile applications created by using
MERN Stack are built much faster, which also helps to provide faster delivery to our clients.
6. Provides faster Modifications: MERN stack technologies supports quick modifications as per
the client's request in the mobile and web applications.
7. Open Source: All the four technologies that are involved in MERN are open-source. This
feature allows developers to get solutions to queries that may evolve from the open portals
during development. As a result, it will be ultimately beneficial for a developer.
8. Easy to switch between client and server: MERN is very simple and fast because it is written
in only one language. And also, it is very easy to switch between client and server.
We already know that it comprises 4 components, i.e., MongoDB, Express.js, React, Node.js.
Now let us understand in more detail about these three tiers which are mentioned above -
i. Web or front-end tier - The top tier of the MERN stack is mainly handled by React.js. It is
one of the most prominent used open-source front-end JavaScript libraries used for building
S.YAMUNADEVI AP/IT 2
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
Web applications. It is famous for creating dynamic client-side applications. React will help
you construct complex interfaces by using single components.
ii. It also connects those complex interfaces to data available on the backend server. React is used
to create mobile applications (React Native) and web applications. React allows the reusability
of code and can easily support it, which has many benefits and is much time saver. It permits
users to create large web applications that can easily change the data of the page even without
reloading the page.
iii. Server or middle-tier - It is just next level from the top layer and is mainly handled by two
components of the MERN stack, i.e., Express.js and Node.js. These two's components handle
it simultaneously because Express.js maintained the Server-side framework, running inside the
Node.js server. Express.js is one of the widely used backend development JavaScript
Frameworks. It allows developers to spin up robust APIs (Application Programming Interface)
and web servers much easier and simpler.
iv. It also adds helpful functionalities to Node.js HTTP (HyperText Transfer Protocol) objects.
Whereas on the other hand, Node.js plays a very important role in itself. It is an open-source
server environment, and it is a cross-platform runtime environment for executing JavaScript
code outside a browser. Node.js continuously uses JavaScript; thus, it's ultimately helpful for a
computer user to quickly create any net service or any net or mobile application.
v.
vi. Database as backend tier - It is one of the most important levels of the MERN Stack and is
mainly handled by MongoDB; the main role of a database is to store all the data related to your
application, for example - content, statistics, information, user profiles, comments and so on. It
mainly stores all the data for safety purposes. It maintains a proper record, which usually
returns the data to the user whenever required. It mainly stores the data in the database. It
generates two or more replica files of the data so that whenever the system fails, it can retrieve
the exact information or data that the user wanted earlier.
vii. It implies that MongoDB is not based on the table-like relational database structure. On the
other hand, it provides an altogether different mechanism for the retrieval and storage of
data. Mongo DB is the most popular NoSQL (NoSQL or Non Structured Query Language)
database, an open-source document-oriented database. The term 'NoSQL' typically means a
non-relational database that does not require a fixed schema or proper relational tables to store
S.YAMUNADEVI AP/IT 3
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
the necessary data in it. MongoDB stores the data in a different format other than the relational
tables, consisting of rows and columns.
Let us understand one by one about the four technologies or components that play a major role in
forming MERN Stack:
I. MongoDB
Mongo DB is the most popular NoSQL (NoSQL or Non Structured Query Language) database,
an open-source document-oriented database.
The term 'NoSQL' typically means a non-relational database that does not require a fixed
schema or proper relational tables to store the necessary data in it. MongoDB stores the data in
a different format other than the relational tables, consisting of rows and columns.
It implies that MongoDB is not based on the table-like relational database structure. On the
other hand, it provides an altogether different mechanism for the retrieval and storage of data.
The storage format in which the data is stored is known as BSON, which stands for Binary
JavaScript Object Notation; its binary structure encodes length and type of information, which
allows it to be parsed much more quickly.
MongoDB uses BSON when storing documents in collections.
It allows a highly scalable and flexible document structure.
It is very faster as compared to RDBMS due to its efficient storage and indexing techniques.
In MongoDB, complex join operations are not available; hence, it cannot support complex
transactions.
MongoDB uses JavaScript for coding as a language which is one of the great advantages.
It is Schemaless as any data stored which is stored in a separate document.
In MongoDB, there is no concept of relationships or table formations, as this is happening in
RDBMS (Relational Database Management System), in which tables have a certain relation
between them.
It also supports a flexible document model, which is very fast for any developer to create.
MongoDB is one of the important types of NoSQL Databases. It is more scalable and provides
excellent performance if we notice that it will reach its scaling limit whenever a database runs
on a single server.
MongoDB is a NoSQL database that scales by adding more and more servers and increases
productivity with its flexible document model.
Features of MongoDB -
❖ Schema-less Database: MongoDB has this one of the great features, which means that one
collection can hold different types of documents in it. Due to this extraordinary feature,
MongoDB provides great flexibility to databases. In the MongoDB database, a single collection
comprises multiple documents, and these documents may further comprise the different
numbers of values, fields, and so on. One document doesn't need to be a must to relate with the
other documents, as it happens in relational databases.
❖ Indexing: In the MongoDB database, one can easily fetch out the necessary data from the data
pool due to this indexing feature. In MongoDB, every data item has provided a particular
S.YAMUNADEVI AP/IT 4
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
index, categorized as primary and secondary indices. With this indexing, data retrieval is easier
for the user; it saves a lot of time. If the data is not indexed, the database searches each
document with the specified query, which takes lots of time and is inefficient.
❖ Document Oriented: In MongoDB, all the data has been stored in documents instead of tables
like SQL. Also, these documents have their unique object id. In these documents, the
informative data is stored in fields, i.e., key-value pairs instead of columns and rows, making
the data much more flexible and easier to fetch out rather than applying queries for every data
compared to RDBMS.
❖ Faster - MongoDB is very fast compared with relational database (RDBMS), which is
document-oriented. Each data item has its index value, making it easier for us to retrieve any
data without wasting time writing queries and making logic accordingly.
❖ Scalability: MongoDB is more scalable with the help of sharding. It provides horizontal
scalability. Here the term sharding means distributing data on multiple servers; in this, a large
amount of data has been divided into multiple small data chunks with the help of shard key.
These types of data chunks are evenly distributed across shards that reside across many
physical servers.
❖ High Performance: MongoDB has very high performance and has data persistency as
compared to other databases due to the presence of its great features like indexing, scalability,
replication, etc.
❖ Replication and Highly Available - MongoDB increases the availability of data due to
creating multiple copies of data on different servers. Providing redundancy or data replication
ultimately protects the database from any hardware failure and protects the data from being lost
in the future. I suppose if one server was not working or clashes due to error, and then data can
easily be retrieved from other active servers, who are currently working at that time, this will
all be due to redundancy of data.
❖ Aggregation: This feature of MongoDB is quite similar to the SQL GROUPBY clause. This
GROUPBY clause performs various operations on the grouped data to get the unique or
computed
❖ Simple Environment Setup - MongoDB has a very simple environment setup. One can easily
set up MongoDB in their system without applying much effort.
II. Express
S.YAMUNADEVI AP/IT 5
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
❖ Express makes Node.js web and mobile application development much easier and faster.
❖ Express has a very simple environment setup. One can easily set up Express in their system and
configure it without applying much effort.
❖ Express is very easy to connect with Databases like MongoDB.
❖ Based on HTTP methods and URLs, Express allows you to define the routes of your
application.
❖ Routing mainly aims to describe code that needs to be run in response to any request received
by a server. Routing is generally done based on the sequence of URL patterns and the HTTP
method, which is associated with the request.
❖ If you want to perform additional tasks and functions on any request and response, you can
easily use various middleware modules present in Express.
❖ The request is a message that arrives at the server for requesting something, and a Response is
a message sent by the server to a client in the form of the result of whatever the client asked
for.
❖ If any error occurs and you want to handle it, you can easily handle it by using error handling
middleware.
❖ Middleware is used somewhere during the lifecycle of request or response in the form of code.
It is mainly used to add functionalities or augment the behaviour of the webserver.
❖ Express also facilitates you to create a REST API (Representational State Transfer Application
Programming Interface)
❖ The REST APIs is also known as RESTful API, It mainly conforms to the constraints of REST
architectural style, and it also allows for interaction with RESTful web services. The main
advantage of REST API is that it provides great flexibility; it uses HTTP requests to access and
use data.
❖ The data flow into a website structure can easily facilitate by using the two template engines,
EJS and Jade, provided by Express.
❖ Express has a gigantic suite of third-party add-ons so that developers can use it to provide
better functionality, helps to increase the security level, and improve speed.
❖ It is very efficient and scalable; one can easily access it from anywhere and use it
simultaneously on different systems, and very fast.
❖ It is Single-threaded and Asynchronous.
❖ It also has the biggest community for Node.js.
❖ With its built-in router, it promotes code reusability.
❖ If we want to understand the architecture behind web servers and their working along with the
organization, then learning Express is the best option.
III. React
❖ React is one of the most popular open-source front-end JavaScript libraries used for building
Web applications.
❖ Before using react, it has some prerequisites that one should follow, that you must download
Node packages in your system with their latest versions. Also, you must have an understanding
of HTML, CSS and JavaScript.
❖ It is used to build user interfaces, especially for a single page web application.
S.YAMUNADEVI AP/IT 6
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
Features of React
❖ Easy to learn - One of the great advantages of using react as it is very easier for a beginner to
learn it and make web and mobile applications using this front-end framework. Anyone with a
piece of previous basic knowledge in programming can easily understand React compared to
Angular. Angular is referred to as a ' Domain Specific Language ', so it is implied that it is
quite difficult to understand it. For Learning React, you need the basic knowledge of CSS and
HTML.
❖ Simple - React is one of the simplest open-source JavaScript front-end frameworks for
building web and mobile applications.
❖ It uses the component-based approach, uses plain and simple JavaScript, and a well-defined
lifecycle, which makes react much simpler and easier. So that one can easily learn it and build
professional mobile and web applications.
❖ It uses a simple syntax named JSX, which allows learners or developers to mix HTML with
JavaScript to make it easier for them to apply and use it for making efficient web and mobile
applications.
❖ Data Binding - React uses an application architecture known as Flux to control data flow to
components via one control point called the dispatcher. It uses one-way data binding, which is
easier to debug self-contained components of large React applications.
❖ Native Approach - React is used to create mobile applications (React Native) and web
applications. React allows the reusability of code and can easily support it, which has many
benefits and is much time saver. So simultaneously, at the same time, we can make IOS, Web
applications and Android.
❖ Performance - React has very fast performance due to the immutability of data. As the name
suggests, we can predict that the immutable data structures never change and allows you to
compare direct object references instead of doing deep-tree comparisons. The above reason
ultimately affects the performance of reacting and makes it faster.
S.YAMUNADEVI AP/IT 7
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
❖ Testability - React is very easy to test; whatever applications we are generating from the react,
whether mobile or web applications, it is much easier for us to test it on react.
❖ There are some state functions in the react, where various react views are treated as these
functions of the states, and we can easily manipulate with the state we pass to the react view.
Also, we can take a look at the output and triggered actions, functions, events, etc.
IV. Node.js
Features of Node.JS:
❖ Easy Scalability: js is highly scalable because it uses a single-threaded model with event
looping. The server usually responds in a non-blocking way due to the help of the event
mechanism. It also makes the server very scalable instead of traditional servers that create
limited threads to handle requests. Node.js uses a single-threaded program, and this program
will be able to provide service to many requests.
❖ Fast: The event loop in Node.js handles all asynchronous operations, so Node.js acts like a fast
suite, and all the operations in Node.js are performed quickly like network connection, reading
or writing in the database, or file system. It runs on the V8 engine developed by Google.
❖ Easy to learn and debug code: js is quite easy to learn and debug because it uses JavaScript
for running code of web-based projects and various web and mobile applications. If you have
excelled in front-end developing and have a good command of JavaScript, you can easily build
and run the application on Node.js and explore more as much you can; it depends on your
capability.
❖ Real-time web apps: js plays a key role in making real-time web applications. And If you are
building a mobile or a web application, you can also use PHP, although it will take the same
time duration as when you use Node.js. Still, if someone wants to build gaming apps and chat
applications, then Node.js is a much better option because of its faster synchronization.
S.YAMUNADEVI AP/IT 8
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
❖ Caching Advantage: js provides the caching property in which a single module is cached.
Sometimes you do not need to re-execute the same lines of code because it has already been
cached using Node.js.
❖ Data Streaming:In Node.js, hypertext transfer protocol ( HTTP ) requests and responses area
unit thought-about as 2 separate events. They're knowledge streams, thus once you method a
file at the time of loading, it'll scale back the time and create it quicker once the info is given
within the style of transmissions. It additionally permits you to stream audio and video files at
lightning speed.
❖ Object-Oriented Approach: A huge complaint against Node.js was its JavaScript heritage,
which frequently involved many procedural spaghetti codes. Frameworks like Coffee Script
and Typescript solved these issues but came as a bolt-on for those who seriously cared about
coding standards. With the release and general adoption of ES6, Classes are built into the
framework, and the code looks syntactically similar to C#, Java and SWIFT.
❖ Event-Driven and Asyncronization- All Apis of the Node.js library area unit asynchronous,
that is, non-blocking. It suggests that a Node.js based mostly server ne'er waits for associate
API to come back knowledge. The server moves to the consequent API once line it, and a
notification mechanism of Events of Node.js helps the server to urge a response from the
previous API decision.
❖ Corporate Support: There are a lot of famous companies like PayPal, Wal-Mart, Microsoft,
Google that are using Node.js for building the applications. Node.js uses JavaScript, so most
companies are combining front-end and backend Teams into a single unit.
There are a lot of advantages of MERN Stack, some of them are mentioned below -
1. For a smooth development of any web application or mobile app, it supports MVC (Model
View Controller) architecture; the main purpose of this architecture is to separate the
presentation details with the business logic.
2. It covers all the web development stages starting from front-end development to backend
development with JavaScript.
3. It is an open-source framework mainly used to develop web-based or mobile applications and
is supported by the community.
4. It is very fast and efficient compared to MEAN Stack and mostly suitable for small
applications, whereas MEAN Stack is suitable for developing large applications.
REACT COMPONENTS:
❖ A Component is one of the core building blocks of React. In other words, we can say that every
application you will develop in React will be made up of pieces called components.
❖ Components make the task of building UIs much easier. Each component exists in the same
space, but they work independently from one another and merge all in a parent component,
which will be the final UI of your application.
❖ Every React component have their own structure, methods as well as APIs. They can be
reusable as per the needs of an application.
S.YAMUNADEVI AP/IT 9
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
Types of Components:
❖ Functional Components
❖ Class Components
Functional Components
❖ In React, function components are a way to write components that only contain a render
method and don't have their own state.
❖ They are simply JavaScript functions that may or may not receive data as parameters.
❖ We can create a function that takes props(properties) as input and returns what should be
rendered.
❖ The functional component is also known as a stateless component because they do not hold or
manage state.
Syntax:
function WelcomeMessage(props) {
S.YAMUNADEVI AP/IT 10
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
}
}
export default App;
Output:
Class Components:
Syntax:
Example:Class component
S.YAMUNADEVI AP/IT 11
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
]
}
}
render() {
return (
<div>
<StudentName/>
<ul>
{this.state.data.map((item) => <List data = {item} />)}
</ul>
</div>
);
}
}
class StudentName extends React.Component {
render() {
return (
<div>
<h1>Student Name Detail</h1>
</div>
);
}
}
class List extends React.Component {
render() {
return (
<ul>
<li>{this.props.data.name}</li>
</ul>
);
}
}
export default App;
Output:
REACT STATE:
❖ The state is an updatable structure that is used to contain data or information about the
component and can change over time.
❖ The change in state can happen as a response to user action or system event. It is the heart of
the react component which determines the behaviour of the component and how it will render.
❖ A state must be kept as simple as possible.
❖ It represents the component's local state or information.
❖ It can only be accessed or modified inside the component or by the component directly.
S.YAMUNADEVI AP/IT 12
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
❖ State can be updated in response to event handlers, server responses, or prop changes. This is
done using the setState() method.
❖ The setState() method enqueues all of the updates made to the component state and instructs
React to re-render the component and its children with the updated state.
❖ Always use the setState() method to change the state object, since it will ensure that the
component knows it’s been updated and calls the render() method.
Props:
❖ Props are read-only components.
❖ It is an object which stores the value of attributes of a tag and work similar to the HTML
attributes.
❖ It allows passing data from one component to other components.
❖ It is similar to function arguments and can be passed to the component the same way as
arguments passed in a function.
❖ Props are immutable so we cannot modify the props from inside the component.
Example:
The following example is for React-State.When the on click event has triggered the state of the
component has changed according to the specification.
S.YAMUNADEVI AP/IT 13
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
);
}
}
Output:
When the change color button has clicked this will returned to the following output:
3. Props allow you to pass data from one State holds information about the
component to other components as an components.
argument.
4. Props can be accessed by the child State cannot be accessed by child
component. components.
5. Props are used to communicate between States can be used for rendering dynamic
components. changes with the component.
6. Stateless component can have Props. Stateless components cannot have State.
8. Props are external and controlled by whatever The State is internal and controlled by
renders the component. the React Component itself.
S.YAMUNADEVI AP/IT 14
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
EXPRESS RESTAPI’S:
❖ Restful API is very popular and commonly used to create APIs for web-based applications.
❖ REST API is the standard way to send and receive data for web services.
❖ REST API is a software that allows two apps to communicate with one another over the
internet and through numerous devices.
GET
❖ used to request data from the server, but mainly this method is used to read data
PATCH
❖ used to update, change or replace the data
POST
❖ used to create new or to edit already existing data
Delete
❖ used to delete the data completely from the server
Step 1: First, open your editor. Now open your terminal and write a command npm init -y
S.YAMUNADEVI AP/IT 15
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
Step 2: Now we will install express for that write command npm install express
Step 3: Now we will create a new file to write all our code index.js Write a few lines of code in the
first line and will import the express packages
Step 5: Then we will write a second argument as a callback to tell the API is working, now lets run this
code to check our API is working or node
Step 6: As our code is running fine, let's open our search engine and write localhost:4000, this will not
run,
S.YAMUNADEVI AP/IT 16
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
MODULARIZATION IN WEBPACK:
Webpack is a JavaScript compiler that converts JS into modularized bundles in preparation for
production.
Webpack used to define entry points for frontend code as well as convert other files to readable
JavaScript and provide the bundle’s path as an output.
Two key elements to interact with the module system:
–require
–exports
Definition for Bundles:
Bundling is the process of following imported files and merging them into a single file: a “bundle”.
The example below is a basic implementation of a `config` object that defines an entry point at
`index.js` in the `src` folder of a web application.
module.exports = {
entry: {
main: './src/index.js'
},
...
}
When it comes to our config module’s `output`, despite an entry’s capability to hold multiple points of
entry, only one output path can be defined. The output property is used to define a destination path for
the newly created JavaScript bundle files as well as a file name. In other words, it defines how and
where to store our compiled code. We can implement this using the Node.js `path` module.
The example below imports the path module as well as store the created `bundle.js` file to the
`dist` folder:
module.exports = {
entry: {
main: './src/index.js'
},
output:
{
path: path.resolve(__dirname, 'dist'),
S.YAMUNADEVI AP/IT 17
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
fileName: 'dist/bundle.js'
}
}
Plugins in Webpack:
❖ When building our Webpack compiler we must also define any loaders and plugins that are
required.
❖ The loader property is used to convert any non-JavaScript files (TypeScript, JSON, CSS, etc.)
into readable, compiled JavaScript.
❖ A different loader is used per file type (i.e. `css-loader` is used for CSS files, style-loader can
handle SCSS, file-loader for handling JSON data, etc.).
❖ They are converted into modules that are added to a dependency graph generated by Webpack.
The example below shows a simple implementation of the loader property:
module.exports = {
input: {
main: './src/index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'dist/bundle.js'
},
module: {
rules: [
{
test: /\.css$/,
use: 'css-loader'
},
{
test: /\.txt$/,
use: 'raw-loader'
},
{
test: /\.ts$/,
use: 'ts-loader'
}
]
}
}
The module object in the example above defines the loaders to use to convert code into JavaScript
modules. These are executed from right to left, or rather, from the bottom to the top, with the last
loader expected to output a JavaScript code. As you can see, different file types require different
loaders. You can even use `module.rules` to chain multiple loaders to a single file-type if needed:
...
module: {
//loaders are executed from right to left/bottom to top
rules: [
S.YAMUNADEVI AP/IT 18
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
{
test: /\.css$/,
use: [
{ loader: 'style-loader' },
//configure loaders with the options property
{
loader: 'css-loader',
options: {
modules: true
}
},
//order of loader import: sass-loader, css-loader,
//style-loader
{
loader: 'sass-loader'
}
]
}
]
}
};
…
Routing is a process in which a user is directed to different pages based on their action or
request. ReactJS Router is mainly used for developing Single Page Web Applications.
React Router is used to define multiple routes in the application. When a user types a specific
URL into the browser, and if this URL path matches any 'route' inside the router file, the user
will be redirected to that particular route.
React Router is a standard library system built on top of the React and used to create routing in
the React application using React Router Package.
It provides the synchronous URL on the browser with data that will be displayed on the web
page.
It maintains the standard structure and behaviour of the application and mainly used for
developing single page web applications.
React Router plays an important role to display multiple views in a single page application.
Without React Router, it is not possible to display multiple views in React applications.
Most of the social media websites like Facebook, Instagram uses React Router for rendering
multiple views.
react-router: It provides the core routing components and functions for the React Router
applications.
react-router-native: It is used for mobile applications.
react-router-dom: It is used for web applications design.
S.YAMUNADEVI AP/IT 19
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
It is not possible to install react-router directly in your application. To use react routing, first, you
need to install react-router-dom modules in your application. The below command is used to install
react router dom.
Example
About.js
Step-2: For Routing, open the index.js file and import all the three component files in it. Here, you
need to import line: import { Route, Link, BrowserRouter as Router } from 'react-router-dom' which
helps us to implement the Routing. Now, our index.js file looks like below.
S.YAMUNADEVI AP/IT 20
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
Index.js
React Router
Now, if you enter manually in the browser: localhost:3000/about, you will see About component is
rendered on the screen.
React Router
Step-4: In the above screen, you can see that Home component is still rendered. It is because the home
path is '/' and about path is '/about', so you can observe that slash is common in both paths which
render both components. To stop this behavior, you need to use the exact prop. It can be seen in the
below example.
Index.js
S.YAMUNADEVI AP/IT 21
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
Server-side rendering (SSR) is a technique of rendering a client-side application on the server before
sending it to the client. This technique can be applied to React-based applications to improve
performance, SEO, and initial load time.
Server-side rendering (SSR) with React is the process of rendering a React-based application on the
server and sending the fully rendered HTML to the client. The client then "hydrates" the static HTML
with the React code to make the application dynamic and interactive.
This approach has several benefits, including improved performance (especially on slow networks),
improved SEO, and the ability to render the initial view of the application on the server, reducing the
time it takes to display the first view on the client. With SSR, the initial HTML and the CSS are
delivered to the client much faster, which provides a better user experience, especially on slower
devices and networks.
There are several situations in which using Server Side Rendering React (SSR) can be beneficial:
S.YAMUNADEVI AP/IT 22
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
Improved Performance
Server Side Rendering with React can improve the performance of your application, especially on
slower networks or devices, as the fully rendered HTML is sent to the client, resulting in faster initial
loading times.
Server Side Rendering React eliminates the need for loaders or spinners during the initial
load. This suggests that, in general, Server Side Rendering will outperform Client Side
Rendering.
Server Side Rendering React applications chunk JavaScript and CSS, optimize assets, and
render pages on the server before providing them to the client browser, leading to a quicker
initial load time.
Faster load speeds result in a better user experience. This is one of the reasons why many
huge corporations are implementing Server Side Rendering React on their website.
Better SEO
Server Side Rendering with React can improve the SEO of your application as search engines
can easily access and crawl the content of the page.
Search engine crawlers may investigate the page with SSR to increase the SEO performance of
your app. This is due to the fact that all pages are rendered on the server with the appropriate
metadata, paragraphs, and headers before being sent to the client, allowing you to reap the
benefits of traditional website SEO.
It's worth noting that, for the time being, Google and Bing can only index synchronous
JavaScript apps.
The crawler will only take a few seconds for loading to complete if your app starts with a
loading spinner and then downloads content using Ajax.
This implies that if you have asynchronously fetched material on pages where SEO is crucial,
SSR may be required.
Better Accessibility
Server Side Rendering with React can improve the accessibility of your application for users
with slow or unreliable internet connections.
Dynamic Data
Server Side Rendering with React can be useful when you want to generate dynamic content on
the server based on data from an API, database, or any other source.
Complex Applications
Server Side Rendering with React can be beneficial for complex applications that require a lot
of data processing on the server.
Security
Server Side Rendering with React can improve the security of your application by allowing you
to run sensitive code on the server, away from the client.
S.YAMUNADEVI AP/IT 23
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
Every page is originally rendered and loaded from the server when using Server Side
Rendering. Things are a little different now that Server Side (universal) React has been
introduced.
The subsequent pages load straight from the client because the first page is rendered from the
server. The strength of the first server-side content combined with the quick subsequent loads,
which only request the content required for future requests, give you the best of both worlds.
The most prevalent way of presenting information on the screen is Server Side Rendering. It
operates by transforming HTML files on the server into information that the browser can use.
When you visit a website, your browser sends a request to the server that houses the website's
content.
The request normally takes only a few milliseconds, however, this is determined by a variety of
factors:
When the request is completed, your browser returns the completely produced HTML and shows it on
the screen. If you then navigate to another page on the website, your browser will make another
request for the updated information. This will happen every time you visit a page for which your
browser does not have a cached version.
Example
Consider this HTML document, which has been put on a fictitious server with the HTTP
address sample.testwebsite.com.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sample Website</title>
</head>
<body>
<h1>Our Sample Website</h1>
<p>Here is a sample of our new website</p>
<a href="http://sample.testwebsite.com/other.html.">Link</a>
</body>
</html>
Step 1: Creating the React App and Modifying the App Component
S.YAMUNADEVI AP/IT 24
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
cd my-app
In this step, you will modify the existing App component to make it suitable for server-side rendering.
Here is the code for the modified App component:
render() {
return (
<div>
<h1>Hello World!</h1>
</div>
);
}
}
S.YAMUNADEVI AP/IT 25
IT3501 FULL STACK WEB DEVELOPMENT PSNACET/IT
Let us now create a webpack.config.js file and add the following configuration:
"scripts": {
"build": "webpack --config webpack.config.js",
"start": "nodemon build/server.js"
},
With these steps, you have configured webpack and Babel to bundle and transpile your server code,
making it ready for execution.
To run the app, you can use the command npm start. The server will be running on port 3000 with all
these done. Now, open http://localhost:3000/ in your web browser and observe your server-side
rendered app.
S.YAMUNADEVI AP/IT 26