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

InP Sem5 final soln

The document provides an overview of key concepts in React, including Hooks, React Router, state management, props, functional components, and component lifecycle methods. It explains the rules for using Hooks, the purpose of React Router for navigation in single-page applications, and how state and props function within components. Additionally, it covers comparisons between technologies like XML and JSON, HTTP and HTTPS, and ES5 and ES6, along with a brief explanation of DNS and asynchronous programming with Promises.

Uploaded by

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

InP Sem5 final soln

The document provides an overview of key concepts in React, including Hooks, React Router, state management, props, functional components, and component lifecycle methods. It explains the rules for using Hooks, the purpose of React Router for navigation in single-page applications, and how state and props function within components. Additionally, it covers comparisons between technologies like XML and JSON, HTTP and HTTPS, and ES5 and ES6, along with a brief explanation of DNS and asynchronous programming with Promises.

Uploaded by

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

Internet Programming Semester Solution-

● Hooks
Hooks are the new feature introduced in the React 16.8 version. It allows you to
use state and other React features without writing a class. Hooks are the functions
which "hook into" React state and lifecycle features from function components. It
does not work inside classes.
Hooks are backward-compatible, which means it does not contain any breaking
changes. Also, it does not replace your knowledge of React concepts.
When to use a Hooks
If you write a function component, and then you want to add some state to it,
previously you do this by converting it to a class. But, now you can do it by using a
Hook inside the existing function component.

Rules of Hooks
Hooks are similar to JavaScript functions, but you need to follow these two rules
when using them.

1. Only call Hooks at


the top level Built-in Hooks
Do not call Hooks Here, we describe the APIs for the built-in Hooks in
inside loops, React. The built-in Hooks can be divided into two
conditions, or nested parts, which are given below.
functions. Hooks
should always be used Basic Hooks –useState, useEffect, useContext
at the top level of the
React functions. This Additional Hooks- useReducer, useCallback,
rule ensures that useMemo, useRef, useImperativeHandle,
Hooks are called in the useLayoutEffect, useDebugValue
same order each time
a components renders.

2. Only call Hooks from ● React Router


React functions Routing is a process in which a user is directed to
different pages based on their action or request.
You cannot call Hooks
ReactJS Router is mainly used for developing Single
from regular JavaScript
functions. Instead, you
Page Web Applications. React Router is used to
can call Hooks from define multiple routes in the application. When a
React function user types a specific URL into the browser, and if this
components. Hooks URL path matches any 'route' inside the router file, the
can also be called from user will be redirected to that particular route.
custom Hooks. 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 maintains the standard structure
and behaviour of the application. E.g. Facebook, Instagram

React contains three different packages for routing. These are:

1. react-router: It provides the core routing components and functions for the
React Router applications.
2. react-router-native: It is used for mobile applications.
3. react-router-dom: It is used for web applications design.

To use react routing, first, you need to install react-router-dom modules in your
application. $ npm install react-router-dom --save

COMPONENTS IN REACT ROUTER


There are two types of router components:
<browserrouter>: it is used for handling the dynamic url.
<hashrouter>: it is used for handling the static request.
Step 3:route: route component will now help us to establish the link between
component’s
UI and the URL. To include routes to the application, add the code give below to
your
app.js.(after </div>)

● States in React
The state is an updatable structure that is used to contain data or information
about the component. The state in a component can change over time. The
change in state over time can happen as a response to user action or system
event. A component with the state is known as stateful components. It is the
heart of the react component which determines the behaviour of the component
and how it will render. They are also responsible for making a component
dynamic and interactive.
It can be set by using the setState() method and calling setState() method
triggers UI updates. It can only be accessed or modified inside the component or
by the component directly. To set an initial state before any interaction occurs,
we need to use the getInitialState() method.

Create class component, use state inside return, add constructor

Index.js, import stateclass


● Props in react
Props stand for "Properties." They 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 gives a way to pass data from one component to other
components. It is similar to function arguments. Props are passed to the
component in the same way as arguments passed in a function.
Props are immutable so we cannot modify the props from inside the
component. Inside the components, we can add attributes called props. These
attributes are available in the component as this.props and can be used to
render dynamic data in our render method.

Example 1: Calling props in function

Add props inside render() function.

Example 2:
● Function component-
ReactJS Functional components are some of the more common components that will come across while
working in React. These are simply JavaScript functions. We can create a functional component in React by
writing a JavaScript function. These functions may or may not receive data as parameters. In the functional
Components, the return value is the JSX code to render to the DOM tree.

Ways to call the functional component:


1. Call the function by using the name of the function followed by the Parentheses.

// Example of Calling
the function with
2. Call the function by using the functional component method.
function name followed
by Parentheses
// Example of Calling
import React from
the function using 1. Comparison between xml ad json.
'react';
component call
import ReactDOM from XML stands for Extensible Markup Language. Provide information
import React from
'react-dom/client'; about a document. Tags are added to the document to provide the
'react';
function Parentheses() extra information. XML is designed to carry data, not to display
import ReactDOM from
{ data. XML is not a replacement for HTML. XML documents are used
'react-dom/client';
return (<h1> to transfer data from one place to another often over the Internet.
function Comp() {
We can call XML properties:
return (<h1> As
function using name of ● Markup language.
usual we can call the
the ● Used for storing and transporting the data.
function using
function
component call</h1>); ● Focuses on data.
followed by
} ● Platform and programming language independent.
Parentheses
const root = ● No predefined tags.
</h1>);
ReactDOM.createRoot(
}
document.getElementB JSON stands for JavaScript Object Notation. It is lightweight data-
const root =
yId('root')); interchange format and easy to read and write than XML. JSON is
ReactDOM.createRoot(
root.render(<Comp />); language independent which supports array, object, string, number
document.getElementB
yId('root')); and values. ×JSON is a syntax for storing and exchanging data. It is
root.render(Parenthese based on a subset of the JavaScript Programming Language. A JSON
s()); filetype is .json. It is originated from JavaScript. In JSON, a map data
structure is used, whereas XML follows a tree structure.
2. Compare between html and xml.

3. Compare between http and https.


HTTPS adds encryption, authentication, and integrity to the HTTP protocol.
Encryption: HTTPS prevents data sent over the internet from being intercepted and read by a
third party
Integrity: a digital signature that a web browser can use to determine that the document has not
been altered by a third party or otherwise corrupted
Authentication: HTTP provides a general framework for access control and authentication.

4. Compare between ES5 and ES6.


5. Explain DNS and its working.
The Domain Name System (DNS) turns domain names into IP addresses, which browsers use to load
internet pages. Every device connected to the internet has its own IP address, which is used by
other devices to locate the device. A DNS server is a computer with a database containing the
public IP addresses associated with the names of the websites an IP address brings a user to. DNS
acts like a phonebook for the internet. Whenever people type domain names, like Google.com or
Yahoo.com, into the address bar of web browsers, the DNS finds the right IP address. The site’s IP
address is what directs the device to go to the correct place to
access the site’s data.
Working: If you wanted to So back to our example, when you type google.com on your web
go to a certain website browser DNS server will search through its cache to find a matching
you would open up your IP address for that domain name, and when it finds it will resolve
web browser and type in that domain name to IP address of Google web site, and once that is
domain name of that done then your computer is able to communicate with a Google
website. Let us use web server and retrieve the webpage.
google.com. Now
technically you really do
not have to type in
google.com to retrieve
6. Arrow function in ES6.
Arrow functions are 7. Promise
introduced in ES6, which
ES6 Promise is the easiest way to work with asynchronous
provides you a more
accurate way to write
programming in JavaScript. Asynchronous programming includes
the functions in JavaScript. the running of processes individually from the main thread and
They allow us to write notifies the main thread when it gets complete. Prior to the
smaller function syntax. Promises, Callbacks were used to perform asynchronous
Arrow functions make your programming. A Callback is a great way when dealing with basic
code more readable and cases like minimal asynchronous operations. But when you are
structured.X developing a web application that has a lot of code, then working
with Callback will be messy. This excessive Callback nesting is often
Arrow functions
referred to as Callback hell.
are anonymous
To deal with such cases, we have to use Promises instead
functions (the functions
of Callbacks.
without a name and not
The Promise represents the completion of an asynchronous
bound with an identifier).
They don't return any operation. It returns a single value based on the operation
value and can declare being rejected or resolved. There are mainly three stages of the
without the function Promise, which are shown below:
keyword. Arrow functions
cannot be used as the
constructors. The context
within the arrow functions
is lexically or statically
defined. They are also
called as Lambda
Functions in different
languages.
Syntax:

const functionNam Pending - It is the initial state of each Promise. It represents that
the result has not been computed yet.
e = (arg1, arg2, ?..) Fulfilled - It means that the operation has completed.
=> { Rejected - It represents a failure that occurs during computation.
//body of the fu Once a Promise is fulfilled or rejected, it will be immutable.
The Promise() constructor takes two arguments that
nction
are rejected function and a resolve function.
} Syntax: const promise = new Promise((resolve,reject) => {....});
There are three parts to an
Arrow Function or Lambda
Function:
▪ Parameters: A

8. Events in JS and its types.


JavaScript's interaction with HTML is handled through events that occur when
the user or the browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that
click too is an event. Other examples include events like pressing any key,
closing a window, resizing a window, etc. Events are a part of the Document
Object Model (DOM) Level 3 and every HTML element contains a set of events
which can trigger JavaScript Code.
Event Handlers
i) a function which runs in case of an event occurs.
ii) block of code that gets executed on the occurrence of an event.

onclick Event Type


This is the most frequently used event type which occurs when a user clicks the left button of his
mouse. You can put your validation, warning etc., against this event type.
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>

<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>
</body>
</html>
onsubmit Event Type
onsubmit is an event that occurs when you try to submit a form. You can put your form validation
against this event type. Here we are calling a validate() function before submitting a form data to
the webserver. If validate() function returns true, the form will be submitted, otherwise it will not
submit the data.
<html>
<head>
<script type = "text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>

<body>
<form method = "POST" action = "t.cgi" onsubmit = "return validate()">
.......
<input type = "submit" value = "Submit" />
</form>
</body>
</html>

onmouseover and onmouseout


These two event types will help you create nice effects with images or even with text as well.
The onmouseover event triggers when you bring your mouse over any element and
the onmouseout triggers when you move your mouse out from that element.

9. React component life cycle.


In ReactJS, every component creation process involves various lifecycle methods.
These lifecycle methods are termed as component's lifecycle. These lifecycle methods
are not very complicated and called at various points during a component's life. The
lifecycle of the component is divided into four phases. They are:
1. Initial Phase
2. Mounting Phase
3. Updating Phase
4. Unmounting Phase

Each phase contains some lifecycle methods that are specific to the particular phase.
Let us discuss each of these phases one by one.

1. Initial Phase
It is the birth phase of the lifecycle of a ReactJS component. Here, the component
starts its journey on a way to the DOM. In this phase, a component contains the
default Props and initial State. These default properties are done in the constructor of
a component. The initial phase only occurs once and consists of the following
methods.
o getDefaultProps()
It is used to specify the default value of this.props. It is invoked before the creation of
the component or any props from the parent is passed into it.
o getInitialState()
It is used to specify the default value of this.state. It is invoked before the creation of
the component.

2. Mounting Phase
In this phase, the instance of a component is created and inserted into the DOM. It
consists of the following methods.
o componentWillMount()
This is invoked immediately before a component gets rendered into the DOM. In the
case, when you call setState() inside this method, the component will not re-render.
o componentDidMount()
This is invoked immediately after a component gets rendered and placed on the DOM.
Now, you can do any DOM querying operations.
o render()
This method is defined in each and every component. It is responsible for returning a
single root HTML node element. If you don't want to render anything, you can return
a null or false value.
3. Updating Phase
It is the next phase of the lifecycle of a react component. Here, we get new Props and
change State. This phase also allows to handle user interaction and provide
communication with the components hierarchy. The main aim of this phase is to
ensure that the component is displaying the latest version of itself. Unlike the Birth or
Death phase, this phase repeats again and again. This phase consists of the following
methods.
o componentWillRecieveProps()
It is invoked when a component receives new props. If you want to update the state in
response to prop changes, you should compare this.props and nextProps to perform
state transition by using this.setState() method.
o shouldComponentUpdate()
It is invoked when a component decides any changes/updation to the DOM. It allows
you to control the component's behavior of updating itself. If this method returns true,
the component will update. Otherwise, the component will skip the updating.
o componentWillUpdate()
It is invoked just before the component updating occurs. Here, you can't change the
component state by invoking this.setState() method. It will not be called,
if shouldComponentUpdate() returns false.
o render()
It is invoked to examine this.props and this.state and return one of the following
types: React elements, Arrays and fragments, Booleans or null, String and Number. If
shouldComponentUpdate() returns false, the code inside render() will be invoked again
to ensure that the component displays itself properly.
o componentDidUpdate()
It is invoked immediately after the component updating occurs. In this method, you can
put any code inside this which you want to execute once the updating occurs. This
method is not invoked for the initial render.

4. Unmounting Phase
It is the final phase of the react component lifecycle. It is called when a component
instance is destroyed and unmounted from the DOM. This phase contains only one
method and is given below.
o componentWillUnmount()
This method is invoked immediately before a component is destroyed and unmounted
permanently. It performs any necessary cleanup related task such as invalidating
timers, event listener, canceling network requests, or cleaning up DOM elements. If a
component instance is unmounted, you cannot mount it again.

10. MVC (model view controller).


Model View
• It is used for all the UI logic of the application.
• All the data-related logic • For example, the Customer view will include all the UI components
that the user works with. such as text boxes, dropdowns, etc. that the final user interacts with.
•Controllers
Represents either the Advantages of MVC
data that is being •Multiple developers can work simultaneously on the model, controller
• It act as an interface and views.
transferred between the
between Model andView •MVC enables logical grouping of related actions on a controller
View and Controller
components together. The views for specific models are also grouped together.
components or any other
• Processlogic-related
business all the business •Models can have multiple views.
logic and incoming
data.
requests 11. Flux
• For example, a •An application architecture that Facebook uses.
• Manipulate
Customer object
datawill
using •Used for building the client-side web application with React.
the Model
retrieve thecomponent
customer • It is not a library nor a framework.
information from the • It is a kind of architecture that complements React as view
• Interact with theViews
database, manipulate it •Follows the concept of Unidirectional Data Flow model.
to render the final output.
and update it data back to • It is useful when the project has dynamic data, and we need to
the
• Fordatabase
example,orthe
use it to keep the data updated in an effective manner.
render
Customer data.
controller will
handle all the interactions
and inputs from the
• It reduces the runtime errors.

Flux applications have three major roles in dealing with data:


1.Dispatcher
2.Stores
3.Views (React components)
12. Refs
How to access Refs
• In React, when a ref is passed to an element inside render method, a reference to the node can be
accessed via the current attribute of the ref.
• Syntax
const node = this.callRef.current;
Example: In this example, we use the refs provided by React, to add a callback function.
// using refs
class App extends React.Component {
constructor() {
super();
this.state = { sayings: "" };
}
update(e) {
this.setState({ sayings: this.refs.anything.value });
}
render() {
return (
<div>
Mukul Says <input type="text" ref="anything"
onChange={this.update.bind(this)} />
<br />
<em>{this.state.sayings}</em>
</div>
);
}
}
ReactDOM.render(< App />, document.getElementById('root'));

13. Explain Asynchronous programming in detail.


Asynchronous programming is a technique that enables your program to start a potentially long-
running task and still be able to be responsive to other events while that task runs, rather than having
to wait until that task has finished. Once that task has finished, your program is presented with the
result.
Example - Synchronously reads the file
•fs.readFileSync()
• Returns contents of file.
node sync.js
var fs = require('fs');
var content = fs.readFileSync("note.txt", "utf8");
console.log(content);
console.log("Reading File");

Example -Asynchronously reads the file


•fs.readFile()
• Returns contents of file.
node async.js
var fs = require('fs');
var content = fs.readFile("note.txt", "utf8",
function(err,content)
{
if(err)
{
return console.log(err);
}
console.log(content);
});
console.log("Reading File");

14. Short note on REPL


REPL (READ, EVAL, PRINT, Getting Started with REPL:
LOOP) is a computer To start working with REPL environment of NODE; open up the
environment similar to terminal (in case of UNIX/LINUX) or the Command prompt (in case
of Windows) and write node and press ‘enter’ to start the REPL.
Shell (Unix/Linux) and
Use ctrl – c to terminate the command and ctrl – c twice to
command prompt. Node
terminate the NODE REPL.
comes with the REPL
environment when it is
installed. System interacts
with the user through
outputs of
commands/expressions
used. It is useful in writing
and debugging the codes.
The work of REPL
Using loops in REPL

15. Explain Nodejs, features of nodejs and types of nodejs module.


Node.js is a cross-platform, open-source server environment that can run on Windows, Linux, Unix,
macOS, and more. Node.js allows you to run JavaScript on the server. It provides an event-driven,
non-blocking (asynchronous) I/O and cross-platform runtime environment for building highly
scalable server-side applications using JavaScript.
Node.js uses asynchronous programming.
Node.js can generate dynamic page content.
Node.js can create, open, read, write, delete, and close files on the server.
Node.js can collect form data.
Node.js can add, delete, modify data in your database.
Features:
▪ Quick execution of code
▪ Uses javascript
▪ Fast data streaming
▪ No buffering
▪ I/O is asynchronous
▪ Cross platform compatibility- means it can run on many operating systems
▪ Scalable- Another of the NodeJS features is scalability. This means that NodeJS can handle a
large number of requests when needed. NodeJS can handle many requests due to its “single
thread event-driven loop”. It also has a cluster module that manages load balancing for all
available CPUs.
▪ Asynchronous and Non-Blocking- NodeJS is a JavaScript environment which uses a single
thread to handle all the requests. All the requests are handled asynchronously, meaning the
client side never needs to wait for data when requested. It also means it is non-blocking; if a
request is being processed in the CPU, the I/O operations are not blocked.
▪ Single-Threaded Working- In Node.js all the requests are single-threads and are collected in
the event loop. This means all the programs are executed in the same thread, from receiving
the request to completing the required task to sending the response to the client back.
Types – core, local and third-party

16. Buffer and Streams in NodeJS.


Node.js servers have to also deal with TCP streams and reading and writing to the filesystem, both
of which make it necessary to deal with purely binary streams of data. To satisfy this need Node.js
use Buffer.
The buffers module provides a way of handling streams of binary data.
The Buffer object is a global object in Node.js, and it is not necessary to import it using
the require keyword.
Buffers only deal with binary data, and it cannot be resizable. Each integer in a buffer represents a
byte.
The syntax for creating an empty Buffer of the length 15:
var buf = Buffer.alloc(15);
Methods to perform the operations on Buffer:

No Method Description

1 Buffer.alloc(size) It creates a buffer and allocates size to it.

2 Buffer.from(initialization) It initializes the buffer with given data.

3 Buffer.write(data) It writes the data on the buffer.

4 toString() It read data from the buffer and returned it.

5 Buffer.isBuffer(object) It checks whether the object is a buffer or not.

6 Buffer.length It returns the length of the buffer.

Node.js streams are a type of data-handling method and are used to read or write input into output
sequentially. Streams are used to handle reading/writing files or exchanging information efficiently.
Streams are collections of data — just like arrays or strings. The difference is that streams might not
be available all at once, and they don’t have to fit in memory. This makes streams really powerful
when working with large amounts of data, or data that’s coming from an external source
one chunk at a time.
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.

// Calling write method with


// Node.js program
to demonstrate
the
// writable.write()
method

// Including stream
module
const stream =
require('stream');

// Creating a
stream and
creating
// a write function
const writable =
new
stream.Writable({

// Write function
with its
// parameters
write:
function(chunk,
encoding, next) {

//
Converting the
chunk of
// data to
string

console.log(chunk.
toString());
next();
}
});

17. Event loop in NodeJS.


The event loop is what allows Node.js to perform non-blocking I/O operations. Most Os are multi-
threaded but nodejs is single-threaded. When one of these operations completes, the kernel tells
Node.js so that the appropriate callback may be added to the poll queue to eventually be executed.
• Event loop is an endless loop, which waits for tasks, executes them and then sleeps until it
receives more tasks.
• The event loop executes tasks from the event queue only when the call stack is empty i.e. there is
no ongoing task.
• The event loop allows us to use callbacks and promises.
• The event loop executes the tasks starting from the oldest first.
timers: this phase executes callbacks scheduled by setTimeout() and setInterval().
pending callbacks: executes I/O callbacks deferred to the next loop iteration.
idle, prepare: only used internally.
poll: retrieve new I/O events; execute I/O related callbacks (almost all with the exception of close
callbacks, the ones scheduled by timers, and setImmediate()); node will block here when
appropriate.
check: setImmediate() callbacks are invoked here.
close callbacks: some close callbacks, e.g. socket.on('close', ...).
┌───────────────────────────┐
┌─>│ timers │
│ └─────────────┬─────────────┘
│ ┌─────────────┴─────────────┐
│ │ pending callbacks │
│ └─────────────┬─────────────┘
│ ┌─────────────┴─────────────┐
│ │ idle, prepare │
│ └─────────────┬─────────────┘ ┌───────────────┐
│ ┌─────────────┴─────────────┐ │ incoming: │
│ │ poll │<─────┤ connections, │
│ └─────────────┬─────────────┘ │ data, etc. │
│ ┌─────────────┴─────────────┐ └───────────────┘
│ │ check │
│ └─────────────┬─────────────┘
│ ┌─────────────┴─────────────┐
└──┤ close callbacks │
└───────────────────────────┘
18. Rest API
19. Short note on Express JS.
Express.js is a small framework that works on top of Node.js web server functionality to simplify its
APIs and add helpful new features. It makes it easier to organize your application’s functionality
with middleware and routing. It adds helpful utilities to Node.js HTTP objects and facilitates the
rendering of dynamic HTTP objects.
▪ Develops Node.js web applications quickly and easily.
▪ It’s simple to set up and personalise.
▪ Allows you to define application routes using HTTP methods and URLs.
▪ Includes a number of middleware modules that can be used to execute additional requests
and responses activities.
▪ Allows you to specify a middleware for handling errors.
▪ Debugging
▪ Faster Server-side Development
Installation-
1. Confirm that node and npm are installed.
node --version
npm --version

2. Create a project directory and create a package.json file


Command - npm init
3. Installation of express
npm install –g express - globally
npm install --save express – locally

4. confirm that Express has installed correctly


ls node_modules #(dir node_modules for windows)

5. Install nodemon
npm install -g nodemon

Create an app- Create a new file called index.js


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

app.get('/’,
function(req, res){
res.send("Hi!");
});

app.listen(3000);
Run the code=> nodemon index.js
20. Explain routing in expressJS with example.
Routing refers to determining how an application responds to a client request to a particular
endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on). Each
route can have one or more handler functions, which are executed when the route is matched.
Route definition takes the following structure:
app.METHOD(PATH, HANDLER)
Where:
● app is an instance of express.
● METHOD is an HTTP request method, in lowercase.
● PATH is a path on the server.
● HANDLER is the function executed when the route is matched.

The following examples illustrate defining simple routes.


Respond with Hello World! on the homepage:
app.get('/', (req, res) => {

res.send('Hello World!')

})

Respond to POST request on the root route (/), the application’s home page:
app.post('/', (req, res) => {

res.send('Got a POST request')

})

Respond to a PUT request to the /user route:


app.put('/user', (req, res) => {

res.send('Got a PUT request at /user')

})

Respond to a DELETE request to the /user route:


app.delete('/user', (req, res) => {

res.send('Got a DELETE request at /user')

})

var express = require('express');


var app = express();
app.get('/', function (req, res) {
console.log("Got a GET request for the homepage");
res.send('Welcome to JavaTpoint!');
})
app.post('/', function (req, res) {
console.log("Got a POST request for the homepage");
res.send('I am Impossible! ');
})
app.delete('/del_student', function (req, res) {
console.log("Got a DELETE request for /del_student");
res.send('I am Deleted!');
})
app.get('/enrolled_student', function (req, res) {
console.log("Got a GET request for /enrolled_student");
res.send('I am an enrolled student.');
})
// This responds a GET request for abcd, abxcd, ab123cd, and so on
app.get('/ab*cd', function(req, res) {
console.log("Got a GET request for /ab*cd");
res.send('Pattern Matched.');
})
var server = app.listen(8000, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})

21. Web browser working


World Wide Web works on the client-server model. A user computer works as a client which can
receive and send data to the server. When a web page is requested by a user, the browser
contacts the requested server (where the website is stored) and by fetching and interpreting the
requested files, it displays the web page on the computer screen.

Fig. 3: Simple Block Diagram Showing Working of Web Browser

Although working of the browser is not as simple as it seems, since a plenty of internal tasks are performed
before a webpage appears on the screen. The whole process takes place in these three steps:
1. Contact to DNS Server – When a user enters a URL into the address bar and hits ‘enter’, at first
browser contacts the DNS server. A DNS server stores the IP addresses of the server associated with the
corresponding domain names. The DNS server takes the domain name from the browser and returns the
corresponding IP address to the browser.

2. Contact to Server – After getting the IP address of the server for the requested webpage,
browser sends a request to that server for the desired files. For example consider the following
URL:
http://www.engineersgarage.com/articles
This URL is divided into three parts. First one is HTTP – it is a protocol named Hyper Text Transfer
Protocol which defines the way browser communicates with the server. The second part is
www.engineersgarage.com which is translated by the DNS server with the IP address. It is the address of a
computer (Web Server) where the requested web page is stored. The third part is ‘articles’ which tells the
address of the file that is located in the root folder of the website.
HTTP protocols are used to transfer the webpage named ‘articles’ to the browser. The protocol decides the
format as well as the methods of communication between web client and server.
Role of Rendering Engine
Once a user requests a particular document, the rendering engine starts fetching the
content of the requested document. This is done via the networking layer. The
rendering engine starts receiving the content of that specific document in chunks of 8
KBs from the networking layer. After this, the basic flow of the rendering engine
begins.

The four basic steps include:

1. The requested HTML page is parsed in chunks, including the external CSS files
and in style elements, by the rendering engine. The HTML elements are then
converted into DOM nodes to form a “content tree” or “DOM tree.”
2. Simultaneously, the browser also creates a render tree. This tree includes both
the styling information as well as the visual instructions that define the order in which
the elements will be displayed. The render tree ensures that the content is displayed
in the desired order.
3. Further, the render tree goes through the layout process. When a render tree
is created, the position or size values are not assigned. The entire process of
calculating values for evaluating the desired position is called a layout process. In this
process, every node is assigned the exact coordinates. This ensures that every node
appears at an accurate position on the screen.
4. The final step is to paint the screen, wherein the render tree is traversed, and
the renderer’s paint() method is invoked, which paints each node on the screen using
the UI backend layer.

You might also like