FSD Material
FSD Material
FSD Material
The main components of a full stack development are the front-end, back-end and database
A tech stack is the combination of technologies a company uses to build and run an application
or project. Sometimes called a “solutions stack,” a tech stack typically consists of programming
languages, frameworks, a database, front-end tools, back-end tools, and applications connected
via APIs.
Most tech stacks are a combination of frontend and backend technologies like JavaScript (user
interface), Python (programming language), MongoDB (database), and Apache (server).
One of the most popular and easiest examples of a technology stack is the MEAN stack. MEAN
stands for MongoDB-Express-Angular-Node.js. You can replace Angular and use React, as in
the MERN stack, since React is becoming equally popular, especially for single page web
applications.
In the above diagram, Node.js is the runtime for the web applications, Angular provides the
user interface, Express is a web framework built over Node.js, and MongoDB is the data
platform or data stack that has the ability to transform data into a more usable form.
The MEAN and MERN stacks are trending tech stacks for web development. Many full-stack
developers find these stacks easy to learn and implement because of the common technology
used throughout the stack: JavaScript.
In general, a tech stack can be a frontend tech stack, backend tech stack, or a mix of both—i.e.,
a full stack.
MERN stands for MongoDB, Express, React, Node, after the four key technologies that make
up the stack.
Express and Node make up the middle (application) tier. Express.js is a server-side web
framework, and Node.js is the popular and powerful JavaScript server platform. Regardless of
which variant you choose, ME(RVA)N is the ideal approach to working with JavaScript and
JSON, all the way through.
The MERN architecture allows you to easily construct a three-tier architecture (front end, back
end, database) entirely using JavaScript and JSON.
The top tier of the MERN stack is React.js, the declarative JavaScript framework for creating
dynamic client-side applications in HTML. React lets you build up complex interfaces through
simple components, connect them to data on your back-end server, and render them as HTML.
React’s strong suit is handling stateful, data-driven interfaces with minimal code and minimal
pain, and it has all the bells and whistles you’d expect from a modern web framework: great
support for forms, error handling, events, lists, and more.
The next level down is the Express.js server-side framework, running inside a Node.js server.
Express.js bills itself as a “fast, unopinionated, minimalist web framework for Node.js,” and
that is indeed exactly what it is. Express.js has powerful models for URL routing (matching an
incoming URL with a server function), and handling HTTP requests and responses.
By making XML HTTP Requests (XHRs) or GETs or POSTs from your React.js front end,
you can connect to Express.js functions that power your application. Those functions, in turn,
use MongoDB’s Node.js drivers, either via callbacks or using promises, to access and update
data in your MongoDB database.
If your application stores any data (user profiles, content, comments, uploads, events, etc.),
then you’re going to want a database that’s just as easy to work with as React, Express, and
Node.
That’s where MongoDB comes in: JSON documents created in your React.js front end can be
sent to the Express.js server, where they can be processed and (assuming they’re valid) stored
directly in MongoDB for later retrieval.
UNIT-1
REACT BASICS
1.1.Introduction
ReactJS is a declarative, efficient, and flexible JavaScript library for building reusable UI
components. It is an open-source, component-based front end library responsible only for the
view layer of the application. It was created by Jordan Walke, who was a software engineer at
Facebook. It was initially developed and maintained by Facebook and was later used in its
products like WhatsApp & Instagram. Facebook developed ReactJS in 2011 in its newsfeed
section, but it was released to the public in the month of May 2013.
Today, most of the websites are built using MVC (model view controller) architecture. In MVC
architecture, React is the 'V' which stands for view, whereas the architecture is provided by the
Redux or Flux.
To create React app, we write React components that correspond to various elements. We
organize these components inside higher level components which define the application
structure. For example, we take a form that consists of many elements like input fields, labels,
or buttons. We can write each element of the form as React components, and then we combine
it into a higher-level component, i.e., the form component itself. The form components would
specify the structure of the form along with elements inside of it.
Therefore, a new technology ReactJS framework invented which remove this drawback.
ReactJS allows you to divide your entire application into various components. ReactJS still
used the same traditional data flow, but it is not directly operating on the browser's Document
Object Model (DOM) immediately; instead, it operates on a virtual DOM. It means rather than
manipulating the document in a browser after changes to our data, it resolves changes on a
DOM built and run entirely in memory. After the virtual DOM has been updated, React
determines what changes made to the actual browser's DOM. The React Virtual DOM exists
entirely in memory and is a representation of the web browser's DOM. Due to this, when we
write a React component, we did not write directly to the DOM; instead, we are writing virtual
components that react will turn into the DOM.
1.2.React Components:
Earlier, the developers write more than thousands of lines of code for developing a single page
application. These applications follow the traditional DOM structure, and making changes in
them was a very challenging task. If any mistake found, it manually searches the entire
application and update accordingly. The component-based approach was introduced to
overcome an issue. In this approach, the entire application is divided into a small logical group
of code, which is known as components.
A Component is considered as the core building blocks of a React application. It makes 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 your need. For better understanding, consider the entire UI as a tree. Here, the
root is the starting component, and each of the other pieces becomes branches, which are further
divided into sub-branches.
React Components
1. Functional Components
2. 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. A valid functional component can be shown in the below
example.
function WelcomeMessage(props) {
return <h1>Welcome to the , {props.name}</h1>;
}
The functional component is also known as a stateless component because they do not hold or
manage state. It can be explained in the below example.
Class Components:
Class components are more complex than functional components. It requires you to extend
from React. Component and create a render function which returns a React element. You can
pass data from one class to other class components. You can create a class by defining a class
that extends Component and has a render function. Valid class component is shown in the
below example.
Example
In this example, we are creating the list of unordered elements, where we will dynamically
insert StudentName for every object from the data array. Here, we are using ES6 arrow syntax
(=>) which looks much cleaner than the old JavaScript syntax. It helps us to create our elements
with fewer lines of code. It is especially useful when we need to create a list with a lot of items.
]
}
}
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;
In React, we can nest components inside within one another. This helps in creating more
complex User Interfaces. The components that are nested inside parent components are called
child components. Import and Export keywords facilitate nesting of the components.
Export - This keyword is used to export a particular module or file and use it in another
module.
Import - This keyword is used to import a particular module or file and use it in the existing
module.
Importing named values allows the user to import multiple objects from a file.
1.4.React Props:
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.
When you need immutable data in the component, you have to add props to reactDom.render()
method in the main.js file of your ReactJS project and used it inside the component in which
you need. It can be explained in the below example.
Example
App.js
Default Props:
It is not necessary to always add props in the reactDom.render() element. You can also set
default props directly on the component constructor. It can be explained in the below
example.
Example
App.js
<h3>Welcome to {this.props.name}</h3>
<p>Skyeagle is one of the best Java training institute in Noida, Delhi, Gurugram,
Ghaziabad and Faridabad.</p>
</div>
);
}
}
App.defaultProps = {
name: "Skyeagle"
}
export default App;
Main.js
ReactDOM.render(<App/>, document.getElementById('app'));
1.5.React State
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 behavior of
the component and how it will render. They are also responsible for making a component
dynamic and interactive.
A state must be kept as simple as possible. It can be set by using the setState() method and
calling setState() method triggers UI updates. A state represents the component's local state or
information. 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.
For example, if we have five components that need data or information from the state, then we
need to create one container component that will keep the state for all of them.
Defining State
To define a state, you have to first declare a default set of values for defining the component's
initial state. To do this, add a class constructor which assigns an initial state using this.state.
The 'this.state' property can be rendered inside render() method.
Example
The below sample code shows how we can create a stateful component using ES6 syntax.
super();
this.state = { displayBio: true };
}
render() {
const bio = this.state.displayBio ? (
<div>
<p><h3>Skyeagle is one of the best Java training institute in Noida, Delhi,
Gurugram, Ghaziabad and Faridabad. We have a team of experienced Java developers and
trainers from multinational companies to teach our campus students.</h3></p>
</div>
) : null;
return (
<div>
<h1> Welcome to </h1>
{ bio }
</div>
);
}
}
export default App;
To set the state, it is required to call the super() method in the constructor. It is because
this.state is uninitialized before the super() method has been called.
this.toggleDisplayBio = this.toggleDisplayBio.bind(this);
Example
In this example, we are going to add a button to the render() method. Clicking on this button
triggers the toggleDisplayBio() method which displays the desired output.
super();
this.state = { displayBio: false };
console.log('Component this', this);
this.toggleDisplayBio = this.toggleDisplayBio.bind(this);
}
toggleDisplayBio(){
this.setState({displayBio: !this.state.displayBio});
}
render() {
return (
<div>
<h1>Welcome to </h1>
{
this.state.displayBio ? (
<div>
<p><h4>Skyeagle is one of the best Java training institute in Noida, Delhi,
Gurugram, Ghaziabad and Faridabad. We have a team of experienced Java developers and
trainers from multinational companies to teach our campus students.</h4></p>
<button onClick={this.toggleDisplayBio}> Show Less </button>
</div>
):(
<div>
<button onClick={this.toggleDisplayBio}> Read More </button>
</div>
)
}
</div>
)
}
}
export default App;
When you click the Read More button, you will get the below output, and when you click the
Show Less button, you will get the output as shown in the above image.
1.6.React JSX
As we have already seen that, all of the React components have a render function. The render
function specifies the HTML output of a React component. JSX(JavaScript Extension), is a
React extension which allows writing JavaScript code that looks like HTML. In other words,
JSX is an HTML-like syntax used by React that extends ECMAScript so that HTML-like
syntax can co-exist with JavaScript/React code. The syntax is used by preprocessors (i.e.,
transpilers like babel) to transform HTML-like syntax into standard JavaScript objects that a
JavaScript engine will parse.
JSX provides you to write HTML/XML-like structures (e.g., DOM-like tree structures) in the
same file where you write JavaScript code, then preprocessor will transform these expressions
into actual JavaScript code. Just like XML/HTML, JSX tags have a tag name, attributes, and
children.
Example
Here, we will write JSX syntax in JSX file and see the corresponding JavaScript code which
transforms by preprocessor(babel).
JSX File
<div>Hello Skyeagle</div>
Corresponding Output
App.JSX
render(){
return(
<div>
<h1>Skyeagle</h1>
<h2>Training Institutes</h2>
</div>
);
JSX Attributes
JSX use attributes with the HTML elements same as regular HTML. JSX uses camelcase
naming convention for attributes rather than standard naming convention of HTML such as a
class in HTML becomes className in JSX because the class is the reserved keyword in
JavaScript. We can also use our own custom attributes in JSX. For custom attributes, we need
to use data- prefix. In the below example, we have used a custom attribute data-demoAttribute
as an attribute for the <p> tag.
Example
import React, { Component } from 'react';
render(){
return(
<div>
<h1>Skyeagle</h1>
<h2>Training Institutes</h2>
</div>
);
render(){
return(
<div>
Skyeagle
This website contains the best CS tutorials.
2. As Expressions: We can specify the values of attributes as expressions using curly braces
{}:
JSX Styling
React always recommends to use inline styles. To set inline styles, you need to use
camelCase syntax. React automatically allows appending px after the number value on
specific elements. The following example shows how to use styling in the element.
Example
import React, { Component } from 'react';
render(){
var myStyle = {
fontSize: 80,
fontFamily: 'Courier',
color: '#003300'
}
return (
<div>
<h1 style = {myStyle}>www.Skyeagle.com</h1>
</div>
);
}
}
export default App;
1.7.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:
Initial Phase
Mounting Phase
Updating Phase
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.
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.
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.
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.
componentDidMount()
This is invoked immediately after a component gets rendered and placed on the DOM. Now,
you can do any DOM querying operations.
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.
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.
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.
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.
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.
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.
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.
Example
import React, { Component } from 'react';
<h3>Hello {this.state.hello}</h3>
<button onClick = {this.changeState}>Click Here!</button>
</div>
);
}
componentWillMount() {
console.log('Component Will MOUNT!')
}
componentDidMount() {
console.log('Component Did MOUNT!')
}
changeState(){
this.setState({hello:"All!!- Its a great reactjs tutorial."});
}
componentWillReceiveProps(newProps) {
console.log('Component Will Recieve Props!')
}
shouldComponentUpdate(newProps, newState) {
return true;
}
componentWillUpdate(nextProps, nextState) {
console.log('Component Will UPDATE!');
}
componentDidUpdate(prevProps, prevState) {
console.log('Component Did UPDATE!')
}
componentWillUnmount() {
console.log('Component Will UNMOUNT!')
}
}
export default App;
UNIT-2
REACT ADVANCED CONCEPTS
2.1.React Events:
An event is an action that could be triggered as a result of the user action or system generated
event. For example, a mouse click, loading of a web page, pressing a key, window resizes, and
other interactions are called events.
React has its own event handling system which is very similar to handling events on DOM
elements. The react event handling system is known as Synthetic Events. The synthetic event
is a cross-browser wrapper of the browser's native event.
React Events
Handling events with react have some syntactic differences from handling events on DOM.
These are:
React events are named as camelCase instead of lowercase.
With JSX, a function is passed as the event handler instead of a string. For example:
Event declaration in plain HTML:
<button onclick="showMessage()">
Hello Skyeagle
</button>
Event declaration in React:
<button onClick={showMessage}>
Hello Skyeagle
</button>
3. In react, we cannot return false to prevent the default behavior. We must call
preventDefault event explicitly to prevent the default behavior. For example:
In plain HTML, to prevent the default link behavior of opening a new page, we can write:
<a href="#" onclick="console.log('You had clicked a Link.'); return false">
Click_Me
</a>
In React, we can write it as:
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('You had clicked a Link.');
}
return (
<a href="#" onClick={handleClick}>
Click_Me
</a>
);
}
In the above example, e is a Synthetic Event which defines according to the W3C spec.
Now let us see how to use Event in React.
Example
In the below example, we have used only one component and adding an onChange event.
This event will trigger the changeText function, which returns the company name.
When you execute the above code, you will get the following output.
2.2.React Forms
Forms are an integral part of any modern web application. It allows the users to interact with
the application as well as gather information from the users. Forms can perform many tasks
that depend on the nature of your business requirements and logic such as authentication of the
user, adding user, searching, filtering, booking, ordering, etc. A form can contain text fields,
buttons, checkbox, radio button, etc.
Creating Form
React offers a stateful, reactive approach to build a form. The component rather than the DOM
usually handles the React form. In React, the form is usually implemented by using controlled
components.
There are mainly two types of form input in React.
Uncontrolled component
Controlled component
Uncontrolled component:
The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles
the form data. Here, the HTML elements maintain their own state that will be updated when
the input value changes. To write an uncontrolled component, you need to use a ref to get form
values from the DOM. In other words, there is no need to write an event handler for every state
update. You can use a ref to access the input field value of the form from the DOM.
Example
In this example, the code accepts a field username and company name in an uncontrolled
component.
render() {
return (
<form onSubmit={this.updateSubmit}>
<h1>Uncontrolled Form Example</h1>
<label>Name:
<input type="text" ref={this.input} />
</label>
<label>
CompanyName:
<input type="text" ref={this.input} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default App;
Controlled Component
In HTML, form elements typically maintain their own state and update it according to the user
input. In the controlled component, the input form element is handled by the component rather
than the DOM. Here, the mutable state is kept in the state property and will be updated only
with setState() method.
Controlled components have functions that govern the data passing into them on every
onChange event, rather than grabbing the data only once, e.g., when you click a submit button.
This data is then saved to state and updated with setState() method. This makes component
have better control over the form elements and data.
A controlled component takes its current value through props and notifies the changes through
callbacks like an onChange event. A parent component "controls" this changes by handling the
callback and managing its own state and then passing the new values as props to the controlled
component. It is also called as a "dumb component."
Example
return (
<form onSubmit={this.handleSubmit}>
<h1>Controlled Form Example</h1>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default App;
Output
When you execute the above code, you will see the following screen.
Example
import React, { Component } from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
personGoing: true,
numberOfPersons: 5
};
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
render() {
return (
<form>
<h1>Multiple Input Controlled Form Example</h1>
<label>
Is Person going:
<input
name="personGoing"
type="checkbox"
checked={this.state.personGoing}
onChange={this.handleInputChange} />
</label>
<br />
<label>
Number of persons:
<input
name="numberOfPersons"
type="number"
value={this.state.numberOfPersons}
onChange={this.handleInputChange} />
</label>
</form>
);
}
}
export default App;
Imagine that you’re building a Datepicker component that takes a few required properties
(not an instance attribute, because that won’t work—instance attributes are set
in constructor() ):
Going back to the earlier example with the Datepicker component and coworkers who aren’t
aware of property types ( "5" versus 5 ), you can set property types to use with React.js
component classes. You do so via the propTypes static attribute. This feature of property types
doesn’t enforce data types on property values and instead gives you a warning. That is, if you’re
in development mode, and a type doesn’t match, you’ll get a warning message in the console
and in production; nothing will be done to prevent the wrong type from being used. In essence,
React.js suppresses this warning in production mode. Thus, propTypes is mostly a
convenience feature to warn you about mismatches in data types at a developmental stage.
3. Rendering children
Let’s continue with the fictional React project; but instead of a Datepicker (which is now
robust and warns you about any missing or incorrect properties), you’re tasked with creating a
component that’s universal enough to use with any children you pass to it. It’s a blog
post Content component that may consist of a heading and a paragraph of text:
<Content>
<h1>React.js</h1>
<p>Rocks</p>
</Content>
The children property is an easy way to render all children with {this.props.children} . You
can also do more than rendering. For example, add a <div> and pass along child elements:
render() {
return (
<div className="content">
{this.props.children}
</div>
ReactDOM.render(
<div>
<Content>
<h1>React</h1>
<p>Rocks</p>
</Content>
</div>,
document.getElementById('content')
A higher-order component (HOC) lets you enhance a component with additional logic You can
think of this pattern as components inheriting functionality when used with HOCs. In other
words, HOCs let you reuse code. This allows you and your team to share functionality among
React.js components.
2.4.REACT ROUTING:
React Router is a standard library for routing in React. It enables the navigation among
views of various components in a React Application, allows changing the browser URL,
and keeps the UI in sync with the URL.
Let us create a simple application to React to understand how the React Router works. The
application will contain three components: home component, about a component, and
contact component. We will use React Router to navigate between these components.
After installing react-router-dom, add its components to your React application.
Adding React Router Components: The main Components of React Router are:
BrowserRouter: BrowserRouter is a router implementation that uses the HTML5
history API(pushState, replaceState and the popstate event) to keep your UI in sync
with the URL. It is the parent component that is used to store all of the other
components.
Routes: It’s a new component introduced in the v6 and a upgrade of the component.
The main advantages of Routes over Switch are:
Relative s and s
Routes are chosen based on the best match instead of being traversed in
order.
Route: Route is the conditionally shown component that renders some UI when its path
matches the current URL.
Link: Link component is used to create links to different routes and implement
navigation around the application. It works like HTML anchor tag.
Using React Router: To use React Router, let us first create few components in the react
application. In your project directory, create a folder named component inside the src folder
and now add 3 files named home.js, about.js and contact.js to the component folder.
Let us add some code to our 3 components:
Home.js
import React from 'react';
function About () {
return <div>
<h2>shri Vishnu engineering college for women</h2>
2.5.REDUX:
What is Redux?
Redux is a predictable state container designed to help you write JavaScript apps that behave
consistently across client, server, and native environments, and are easy to test.
With Redux, the state of your application is kept in a store, and each component can access
any state that it needs from this store.
Without Redux, you would have to make data dependent on the components and pass it
through different components to where it’s needed.
WITHOUT REDUX
In our example above, we only need some data in the parent and inner child components, but
we’re forced to pass it to all the components (including the child component that doesn’t need
it) to get it to where it’s needed.
With Redux, we can make state data independent of the components, and when needed, a
component can access or update through the Redux store.
WITH REDUX
What is state management in Redux?
State management is essentially a way to facilitate communication and sharing of data across
components. It creates a tangible data structure to represent the state of your app that you can
read from and write to. That way, you can see otherwise invisible states while you’re working
with them.
Most libraries, such as React, Angular, etc. are built with a way for components to internally
manage their state without any need for an external library or tool. It does well for applications
with few components, but as the application grows bigger, managing states shared across
components becomes a chore.
In an app where data is shared among components, it might be confusing to actually know
where a state should live. Ideally, the data in a component should live in just one component,
so sharing data among sibling components becomes difficult.
For instance, in React, to share data among siblings, a state has to live in the parent component.
A method for updating this state is provided by the parent component and passed as props to
these sibling components.
Here’s a simple example of a login component in React. The input of the login component
affects what is displayed by its sibling component, the status component:
render() {
return (
<div>
// the state is passed to the sibling as a props as is
updated whenever
// the child component changes the input
<Status status={this.state.userStatus} />
// this method is passed to the child component as a props
which it
// uses to change the state of the userStatus
<Login handleSubmit={this.setStatus} />
</div>
);
}
});
Basically, the state will have to be lifted up to the nearest parent component and to the next
until it gets to an ancestor that is common to both components that need the state, and then it
is passed down. This makes the state difficult to maintain and less predictable. It also means
passing data to components that do not need it.
It’s clear that state management gets messy as the app gets complex. This is why you need a
state management tool like Redux that makes it easier to maintain these states. Let’s get a good
overview of Redux concepts before considering its benefits.
They are the only way you can send data from your application to your Redux store. The data
can be from user interactions, API calls, or even form submissions.
{
type: "LOGIN",
payload: {
username: "foo",
password: "bar"
}
}
What are Redux reducers?
Reducers are pure functions that take the current state of an application, perform an action,
and return a new state. The reducer handles how the state (application data) will change in
response to an action.
if (user.password == action.password) {
return {
...user,
login_status: "LOGGED IN"
}
}
});
default:
return state;
} };
What is Redux Store?
The store is a “container” (really a JavaScript object) that holds the application state, and the
only way the state can change is through actions dispatched to the store. Redux allows
individual components connect to the store and apply changes to it by dispatching actions.
It is highly recommended to keep only one store in any Redux application. You can access
the state stored, update the state, and register or unregister listeners via helper methods.
Ease of Learning: React JS has a short learning curve as compared to other front-end
libraries or frameworks, hence any developer with a basic knowledge of JavaScript can start
learning and building apps using React JS in a short period of time.
Quick Rendering: React JS uses virtual DOM and algorithms like diffing, which makes the
development process fast and efficient.
One-way data-binding: React JS follows one-way data binding, which means you get more
control over the flow of the application.
High Performance: The best advantage of React JS is its performance. There are many
features that make it possible:
o React uses virtual DOM, which enables the re-rendering of nodes only when they are
required to.
o React JS also supports bundling and tree shaking, which minimizes the end user’s resource
load.
This tutorial deep dives into performing unit testing of React Apps using JEST.
Process Becomes Agile: Agile Testing process is the main advantage of unit testing. When
you add more features to the software, it might affect the older designs and you might need to
make changes to the old design and code later. This can be expensive and require extra effort.
But if you do unit testing, the whole process becomes much faster and easier.
Quality of code: Unit testing significantly improves the quality of the code. It helps
developers to identify the smallest defects that can be present in the units before they go for
the integration testing.
Facilitates change: Refactoring the code or updating the system library becomes much easier
when you test each component of the app individually.
Smooth Debugging: The debugging process is very simplified by doing unit testing. If a
certain test fails, then only the latest changes that have been made to the code need to be
debugged.
Reduction in cost: When bugs are detected at an early stage, through unit testing, they can
be fixed at almost no cost as compared to a later stage, let’s say during production, which can
be really expensive.
Open the package.json, and you will find that when you use create-react-app for creating a
react project, it has default support for jest and react testing library. This means that we do
not have to install them manually.
Step 2: Create a component
Let’s create a component called Counter, which simply increases and decreases a numeric
value at the click of respective buttons.
import React, { useState } from "react";
};
};
return (
<>
</button>
<p data-testid="counter">{counter}</p>
</button>
</>
);
};
//test block
render(<Counter />);
fireEvent.click(incrementBtn);
expect(counter).toHaveTextContent("1");
});
Note: In order to let jest know about this test file, it’s important to use the extension .test.js.
The above test can be described as:
The test block can be written either using test() or it(). Either of the two methods takes two
parameters:
o The first parameter is to name the test. For example, increments counter.
o The second parameter is a callback function, which describes the actual test.
Using the render() method from the react testing library in the above test to render the
Counter component in a virtual DOM.
The screen property from the react testing library helps select the elements needed to test by
the test ids provided earlier.
To interact with the button, using the fireEvent property from the react testing library in the
test.
And finally, it is asserted that the counter element will contain a value ‘1’.
Step 4: Run the test
Run the test using the following command:
npm run test
Test Result
UNIT-3
Node.js
3.1.NODE.JS INTRODUCTION:
Node.js is an open-source server side runtime environment built on Chrome's V8 JavaScript
engine. It provides an event driven, non-blocking (asynchronous) I/O and cross-platform
runtime environment for building highly scalable server-side application using JavaScript.
Node.js can be used to build different types of applications such as command line
application, web application, real-time chat application, REST API server etc. However, it
is mainly used to build network programs like web servers, similar to PHP, Java, or
ASP.NET.
Advantages of Node.js
1. Node.js is an open-source framework under MIT license. (MIT license is a free software
license originating at the Massachusetts Institute of Technology (MIT).)
2. Uses JavaScript to build entire server side application.
3. Lightweight framework that includes bare minimum modules. Other modules can be
included as per the need of an application.
4. Asynchronous by default. So it performs faster than other frameworks.
5. Cross-platform framework that runs on Windows, MAC or Linux
3.2.Node.js Module
Module in Node.js is a simple or complex functionality organized in single or multiple
JavaScript files which can be reused throughout the Node.js application.
Each module in Node.js has its own context, so it cannot interfere with other modules or
pollute global scope. Also, each module can be placed in a separate .js file under a separate
folder.
1. Core Modules
2. Local Modules
3. Third Party Modules
The following table lists some of the important core modules in Node.js.
http http module includes classes, methods and events to create Node.js http server.
url url module includes methods for URL resolution and parsing.
fs fs module includes classes, methods, and events to work with file I/O.
In order to use Node.js core or NPM modules, you first need to import it using require()
function as shown below.
As per above syntax, specify the module name in the require() function. The require()
function will return an object, function, property or any other JavaScript type, depending on
what the specified module returns.
The following example demonstrates how to use Node.js http module to create a web server.
});
server.listen(5000);
In the above example, require() function returns an object because http module returns its
functionality as an object, you can then use its properties and methods using dot notation
e.g. http.createServer().
Local modules are modules created locally in your Node.js application. These modules
include different functionalities of your application in separate files and folders. You can
also package it and distribute it via NPM, so that Node.js community can use it. For example,
if you need to connect to MongoDB and fetch data then you can create a module for it, which
can be reused in your application.
Let's write simple logging module which logs the information, warning or error to the
console.
In Node.js, module should be placed in a separate JavaScript file. So, create a Log.js file
and write the following code in it.
Log.js
var log = {
info: function (info) {
console.log('Info: ' + info);
},
warning:function (warning) {
console.log('Warning: ' + warning);
},
error:function (error) {
console.log('Error: ' + error);
}
};
module.exports = log
In the above example of logging module, we have created an object with three functions -
info(), warning() and error(). At the end, we have assigned this object to module.exports.
The module.exports in the above example exposes a log object as a module.
The module.exports is a special object which is included in every JS file in the Node.js
application by default. Use module.exports or exports to expose a function, object or
variable as a module in Node.js.
Now, let's see how to use the above logging module in our application.
To use local modules in your application, you need to load it using require() function in the
same way as core module. However, you need to specify the path of JavaScript file of the
module.
The following example demonstrates how to use the above logging module contained in
Log.js.
app.js
myLogModule.info('Node.js started');
In the above example, app.js is using log module. First, it loads the logging module using
require() function and specified path where logging module is stored. Logging module is
contained in Log.js file in the root folder. So, we have specified the path './Log.js' in the
require() function. The '.' denotes a root folder.
The require() function returns a log object because logging module exposes an object in
Log.js using module.exports. So now you can use logging module as an object and call any
of its function using dot notation e.g myLogModule.info() or myLogModule.warning() or
myLogModule.error()
Run the above example using command prompt (in Windows) as shown below.
Thus, you can create a local module using module.exports and use it in your application.
Here, you will learn how to expose different types as a module using module.exports.
The module.exports is a special object which is included in every JavaScript file in the
Node.js application by default. The module is a variable that represents the current module,
and exports is an object that will be exposed as a module. So, whatever you assign
to module.exports will be exposed as a module.
Export Literals
Message.js
app.js
console.log(msg);
Run the above example and see the result, as shown below.
Hello World
NPM is included with Node.js installation. After you install Node.js, verify NPM installation
by writing the following command in terminal or command prompt.
C:\>npm -v
If you have an older version of NPM then you can update it to the latest version using the
following command.
C:/> npm install npm -g
To access NPM help, write npm help in the command prompt or terminal window.
NPM performs the operation in two modes: global and local. In the global mode, NPM
performs operations which affect all the Node.js applications on the computer whereas in
the local mode, NPM performs operations for the particular local directory which affects an
application in that directory only.
Use the following command to install any third party module in your local Node.js project
folder.
For example, the following command will install ExpressJS into MyNodeProj folder.
All the modules installed using NPM are installed under node_modules folder. The above
command will create ExpressJS folder under node_modules folder in the root folder of your
project and install Express.js there.
Use --save at the end of the install command to add dependency entry into package.json of
your application.
For example, the following command will install ExpressJS in your application and also
adds dependency entry into the package.json.
NPM can also install packages globally so that all the node.js application on that computer
can import and use the installed packages. NPM installs global packages
into /<User>/local/lib/node_modules folder.
Apply -g in the install command to install package globally. For example, the following
command will install ExpressJS globally.
Update Package
To update the package installed locally in your Node.js project, navigate the command
prompt or terminal window path to the project folder and write the following update
command.
The following command will update the existing ExpressJS module to the latest version.
Uninstall Packages
Use the following command to remove a local package from your project.
node -v
npm -v
Your output should be similar to the image below:
Terminal showing
the versions of node and npm
The version may be different but that's OK.
mkdir server-tut
cd server-tut
In the terminal, type npm init. Hit the Enter button for all prompts. When completed, you
should have a package.json file seated in your project directory.
The package.json file is just a file with all the details of your project. You don't have to open
it.
Create a file called index.js.
In the file, require the HTTP module like so:
const http = require('http');
Call the createServer() method on it and assign it to a constant like this:
const server = http.createServer();
Call the listen() method on the server constant like this:
server.listen();
Give it a port to listen to. Now this could be any free port, but we will be using
port 3000 which is the conventional port. So we have this:
const http = require('http');
server.listen(3000);
Basically, that is all you need do to create a server.
server.listen(3000);
In basic terms, the request object tells the server that we want something, the response object
tells us what the server has to say about our request, and the end() method terminates the
communication with the server response.
Hopefully, that makes sense!
Now, test the server again following the steps we outlined above and your server should be
talking to you. This is my output:
Use Control/Command + C to terminate the server and run node index to start the server
again.
How to Create a Node Server With Express
In this section, we want to make our lives easier by using Express and Nodemon (node-mon
or no-demon, pronounce it as you wish).
In the terminal, install the following:
In the file,
module.exports = app;
So we have:
app.set('port', 3000);
And replace the code in the http.createServer() method with just app like this:
const server = http.createServer(app);
This directs all API management to the app.js file helping with separation of concerns.
So our index.js file now looks like this:
const http = require('http');
const app = require('./app');
app.set('port', 3000);
const server = http.createServer(app);
server.listen(3000);
Back in our app.js file, since we have directed all API management to it, let's create an
endpoint to speak to us like before.
So before the module.exports = app, add the following code:
app.use((request, response) => {
response.json({ message: 'Hey! This is your server response!' });
});
We now have:
module.exports = app;
Ahaaa... It's time to test our app.
To test our app, we now type nodemon index in our terminal and hit the Enter button. This is
my terminal:
Do you notice that nodemon gives us details of execution in the terminal unlike Node? That's
the beauty of nodemon.
You can now go to postman or any browser and in the address bar,
type http://localhost:3000/ and hit Enter. See my output:
Now more reasons to use nodemon. Go to the app.js file and change the message string to
any string on your choice, save, and watch the terminal.
Wow... It automatically restarts the server. This was impossible with Node. We had to restart
the server ourselves.
3.6.Node.js Debugging:
Debugging is a concept to identify and remove errors from software applications. In this
article, we will learn about the technique to debug a Node.js application.
Why not to use console.log()?
Using console.log to debug the code generally dives into an infinite loop of “stopping the
app and adding a console.log, and start the app again” operations. Besides slowing down
the development of the app, it also makes the writing dirty and creates unnecessary code.
Finally, trying to log out variables alongside with the noise of other potential logging
operations, may make the process of debugging difficult when attempting to find the values
you are debugging.
How to debug?
Mostly we used console.log() but as mentioned above, it is not always a good practice. We
can use a V8 inspector for it.
Steps for debugging:
1. Write the following code in the terminal window as shown below:
node --inspect-brk-filename.js
4. Now, click on the Node.js icon. The terminal will show the following message:
const dp = require('chrome-remote-interface');
await Profiler.enable();
await Profiler.setSamplingInterval({interval: 500});
await Profiler.start();
await Runtime.evaluate({expression: 'startTest();'});
await sleep(800);
test().then((result)=>{
console.log(result);
})
.catch((error)=>{
console.log(error);
});
const fs = require('fs');
session.connect();
session.post('Profiler.enable');
session.post('Profiler.start');
setTimeout( function() {
session.post('Profiler.stop',
function(err, data) {
fs.writeFileSync('data.cpuprofile',
JSON.stringify(data.profile));
});
}, 8000);
Another awesome thing in using Chrome as a debugging tool is that you can debug both
your front-end and back-end JavaScript code with the same interface.
3.7.What is inspector in Node.js?
Inspector in node.js is a debugging interface for node.js application that is contained in the
app.js file and used blink developer tools. It works almost similar to chrome developer
tools. It can support almost all the feature that a debugger generally have such as navigating
to source files, setting breakpoints, CPU and heap profiling, network client requests
inspection, console output inspections, and many other features.
How to install?
It can be installed by running the following command in the command line after installing
npm (node package manager).
$ npm install -g node-inspector
Here in the command, -g flag corresponds to global installation of the inspector. After
installing if you run command node-inspector, we get an output like this:
In the above figure, it displays an URL for debugging purpose. So, when we point our
browser to http://127.0.0.1:8080/?port=5858, we get a GUI for debugging. Sometimes,
port 8080 may not be available on the computer then we will get an error. We can change
the port (in this case port 5555) on which node-inspector is running by using the following
command:
$ node-inspector --web-port=5555
How to start using it?
It can be started using following command in command line:
$ node-debug app.js
where app.js is the name of the main JavaScript application file. Available configuration
options can be seen here.
The node-debug command will load Node Inspector in the default browser.
Note: Node Inspector works in Chrome and Opera only.
Advanced Use: While running node-debug is an easy way to start your debugging session,
sometimes we need to tweak the default setup. Then we need to follow three steps given
below
1. Start the node-inspector server: This can be done by running command:
$ node-inspector
The server can be left running in the background, it is possible to debug multiple
processes using the same server instance.
2. Enable debug mode in the node process: You can either start Node with a debug flag
like:
$ node --debug your/node/program.js
or, to pause your script on the first line:
$ node --debug-brk your/short/node/script.js
Or one can enable debugging on a node that is already running by sending it a signal:
1. Get the PID of the node process using your favorite method. pgrep or ps -ef are
good.
$ pgrep -l node
2345 node your/node/server.js
2. Send it the USR1 signal
$ kill -s USR1 2345
3. Load the debugger UI: Open http://127.0.0.1:8080/?port=5858 or the produced URL
in the Chrome browser.
Node.js is a widely used javascript library based on Chrome’s V8 JavaScript engine for
developing server-side applications in web development.
3.8.TESTING IN NODE.JS
Unit Testing is a software testing method where individual units/components are tested in
isolation. A unit can be described as the smallest testable part of code in an application.
Unit testing is generally carried out by developers during the development phase of an
application.
In Node.js there are many frameworks available for running unit tests. Some of them are:
Mocha
Jest
Jasmine
AVA
Unit testing for a node application using these frameworks:
1. Mocha: Mocha is an old and widely used testing framework for node applications. It
supports asynchronous operations like callbacks, promises, and async/await. It is a
highly extensible and customizable framework that supports different assertions and
mocking libraries.
To install it, open command prompt and type the following command:
# Installs globally
npm install mocha -g
# installs in the current directory
npm install mocha --save-dev
How to use Mocha?
In order to use this framework in your application:
1. Open the root folder of your project and create a new folder called test in it.
2. Inside the test folder, create a new file called test.js which will contain all the code
related to testing.
3. open package.json and add the following line in the scripts block.
4. "scripts": {
5. "test": "mocha --recursive --exit"
}
Example:
// Requiring module
const assert = require('assert');
after(() => {
console.log( "This part executes once after all tests" );
});
describe("Test2", () => {
beforeEach(() => {
console.log( "executes before every test" );
});
Copy the above code and paste it in the test.js file that we have created before. To run
these tests, open the command prompt in the root directory of the project and type the
following command:
npm run test
Output:
What is Chai?
Chai is an assertion library that is often used alongside Mocha. It can be used as a TTD
(Test Driven Development) / BDD (Behavior Driven Development) assertion library for
Node.js that can be paired up with any testing framework based on JavaScript. Similar
to assert.equal() statement in the above code, we can use Chai to write tests like English
sentences.
To install it, open the command prompt in the root directory of the project and type the
following command:
npm install chai
Example:
Output:
2. Jest: Jest is also a popular testing framework that is known for its simplicity. It is
developed and maintained regularly by Facebook. One of the key features of jest is it is
well documented, and it supports parallel test running i.e. each test will run in their own
processes to maximize performance. It also includes several features like test watching,
coverage, and snapshots.
You can install it using the following command:
npm install --save-dev jest
Note: By default, Jest expects to find all the test files in a folder called “__tests__” in
your root folder.
Example:
Output:
3. Jasmine: Jasmine is also a powerful testing framework and has been around since
2010. It is a Behaviour Driven Development(BDD) framework for testing JavaScript
code. It is known for its compatibility and flexibility with other testing frameworks like
Sinon and Chai. Here test files must have a specific suffix (*spec.js).
You can install it using the following command:
describe("Test", function() {
it("Addition", function() {
var sum = 2 + 3;
expect(sum).toEqual(5);
});
});
4. AVA: AVA is a relatively new minimalistic framework that allows you to run your
JavaScript tests concurrently. Like the Jest framework, it also supports snapshots and
parallel processing which makes it relatively fast compared to other frameworks. The
key features include having no implicit globals and built-in support for asynchronous
functions.
You can install it using the following command:
npm init ava
Example:
test('Addition', t => {
t.is(2 + 3, 5);
});
Unit-4
Mongo DB
4.1.What is Mongo DB?
Mongo DB Atlas is a cloud database solution for contemporary applications that is available
globally. This best-in-class automation and established practices offer to deploy fully managed
Mongo DB across AWS, Google Cloud, and Azure.
It also ensures availability, scalability, and compliance with the most stringent data security
and privacy requirements. Mongo DB Cloud is a unified data platform that includes a global
cloud database, search, data lake, mobile, and application services
4.2.History of Mongo DB
Dwight Merriman, Eliot Horowitz, and Kevin Ryan created Mongo DB in 2007. To provide a
solution for the problems of scalability and agility that they were facing at DoubleClick, they
decided to develop a database. That’s when Mongo DB came into existence.
This is different than SQL databases like MySQL and PostgreSQL, where fields correspond
to columns in a table and individual records correspond to rows.
Prerequisites
You should have a general familiarity with the Windows command prompt.
Download the MongoDB installer file from the downloads section of the MongoDB
website.
Find the dowloaded .msi file in the Windows Explorer. Double click the file and follow
the prompts to install Mongo. Note: unless you specify a custom directory Mongo is most
likely installed in the C:\mongodb directory**. However, based on settings on your
machine Mongo may be installed other places. For example, C:\Program
Files\MongoDB\Server\3.2 . Additionally, you may find MongoDB in the add/remove
programs menu.
Create the directory where MongoDB will store it’s files. From the command prompt
run md \data\db . This is the default location. However, other locations can be specified
using the --dbpath parameter. See the Mongo docs for more information.
Connect to MongoDB using the Mongo shell While the MongoDB daemon is running,
from a different Command prompt window run C:\mongodb\bin\mongo.exe
mongo --version
4.4.MongoDB Shell
MongoDB have a JavaScript shell that allows interaction with MongoDB instance from the
command line.
If you want to create a table, you should name the table and define its column and each column's
data type.
The shell is useful for performing administrative functions and running instances.
To start the shell, open command prompt, run it as a administrator then run the mongo
executable:
1. $ mongo
You should start mongoDB before starting the shell because shell automatically attempt to
connect to a MongoDB server on startup.
1. >x= 100
2. 100
3. >x/ 5;
4. 20
Hello, MongoDB!
Note: You can create multiple commands.
When you press "Enter", the shell detect whether the JavaScript statement is complete or not.
If the statement is not completed, the shell allows you to continue writing it on the next line. If
you press "Enter" three times in a row, it will cancel the half-formed command and get you
back to the > - prompt.
collection to store N number of records that are documented. Collection stores N number of
documents. MongoDB accepts unstructured data. Document stores data which is not in
column and datatype 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. We should first create a database to store the collection value.
A) Create a Collection
1. We have created a database named hospital.
Code:
use hospital
Output:
If we don’t enter any value inside (), then an error will appear. Error: no object passed
to insert!
3. We have inserted a record for the patient with field: value pair.
Code:
db.patient.insert({name:'akash',age:23,reason:'fever'})
Be careful while creating record because if we don’t use ( ‘ ‘) for the string, then an error will appear.
Code:
db.patienthistory.drop()
Output:
3. If we try to delete the non-existing collection, then the false message is displayed.
Code:
db.library.drop()
Output:
1. Find ()
1. This command will display data from collection means documents/records inserted into the
collection.
Syntax:
db.collection_name.find()
Code:
db.patient.find()
_id – it is defined for each document by default if we do not mention it while creating a document.
We have inserted name, age and reason for each patient.
We can observe that no data is present in the first record because we have created a document
without field: value pair.
Output:
2. Filtering collection
If we have a huge dataset and want to find a particular value or fetch certain records, then find () will
help us.
Syntax:
db.collection_name.find({field:value})
Code:
db.patient.find({name:"akash"})
Output: It has fetched all the details of Akash from the patient collection.
4.6.CRUD OPERATIONS
MongoDB is a document database. A record in MongoDB is a document, which is a data
structure composed of key value pairs similar to the structure of JSON objects.
Records in a MongoDB database are called documents, and the field values may include
numbers, strings, booleans, arrays, or even nested documents.
category: "News",
likes: 1,
date: Date()
Create a Database
use blog
switched to db blog
Create Collection using mongosh
Method 1
Example
db.createCollection("posts")
Method 2
Example
We are here assuming object is a valid JavaScript object containing post data:
db.posts.insertOne(object)
MongoDB mongosh Insert
Insert Documents
insertOne()
db.posts.insertOne({
category: "News",
likes: 1,
date: Date()
})
insertMany()
db.posts.insertMany([
category: "Event",
likes: 2,
date: Date()
},
category: "Technology",
likes: 3,
date: Date()
},
category: "Event",
likes: 4,
date: Date()
])
find()
To select data from a collection in MongoDB, we can use the find() method.
This method accepts a query object. If left empty, all documents will be returned.
db.posts.find()
findOne()
This method accepts a query object. If left empty, it will return the first document it finds.
db.posts.findOne()
Update Document
The first parameter is a query object to define which document or documents should be
updated.
updateOne()
The updateOne() method will update the first document that is found matching the provided
query.
Let's see what the "like" count for the post with the title of "Post Title 1":
Delete Documents
These methods accept a query object. The matching documents will be deleted.
deleteOne()
The deleteOne() method will delete the first document that matches the query provided.
deleteMany()
The deleteMany() method will delete all documents that match the query provided.
mongoose.connect('mongodb://127.0.0.1:27017/myapp');
This is the minimum needed to connect the myapp database running locally on the default
port (27017). If connecting fails on your machine, try using 127.0.0.1 instead of localhost.
mongoose.connect('mongodb://username:password@host:port/database?options...');
Buffering
Error Handling
Options
Connection String Options
Connection Events
A note about keepAlive
Server Selection
Replica Set Connections
Replica Set Host Names
Multi-mongos support
Multiple connections
Connection Pools
and GCP) including a multi-cloud setup should you wish to target specific regions or data
centers across providers.
Database-as-a-Service (DBaaS) is a service that allows you to set up, deploy, and scale a
database without worrying about on-premise physical hardware, software updates, and the
details of configuring for performance. With DBaaS, a cloud provider does all that for you—
and gets you up and running right away.
MongoDB Atlas is a fully-managed cloud database that handles all the complexity of
deploying, managing, and healing your deployments on the cloud service provider of your
choice (AWS , Azure, and GCP). MongoDB Atlas is the best way to deploy, run, and scale
MongoDB in the cloud. With Atlas, you’ll have a MongoDB database running with just a few
clicks, and in just a few minutes.
MongoDB Atlas has a free tier, so you won’t need any payment or credit card information.
Registration
You can sign up using your Google account. This would be the preferred method; however,
you can also register using your email address.
At the end of the sign-up process, you will be prompted to create an organization and a
project.
Organizations allow you to group and define users and teams, and grant them access to the
different projects.
Projects allow you to define and organize resources such as database clusters, triggers, and
data lakes. A common way to use projects is to define each environment as a project. For
example, you can have a separate project for development, testing, and production.
You can skip this step and go directly to the management console for MongoDB Atlas. But
you will need an organization and a project in order to create a database cluster, so it makes
sense to do this step now. If you decide to skip it, you’ll be able to create an organization and
a project later.
Once you have an Atlas account and have created an organization and a project, you’ll be
able to create a database cluster.
Make sure you have the desired organization and project selected in the top navigation
dropdowns. Then, select “Clusters” from the left navigation menu and click on the Build a
Cluster button.
You’ll be presented with a choice of Shared Cluster, Dedicated Cluster, and Multi-Cloud &
Multi-Region Cluster.
Shared Cluster is the least expensive (or free, depending on the usage) but it utilizes shared
hardware resources and network.
Dedicated Cluster provides you with a dedicated set of hardware and network isolation as
well as the option to scale automatically within a single region.
The Multi-Cloud & Multi-Region Cluster builds on top of what the dedicated cluster
provides. It offers the best availability since it can replicate data across multiple geographic
regions. It also allows the creation of multi-cloud clusters using any combination of cloud
providers: AWS, Azure, and GCP.
If you’d like to explore a little with the free tier, select the Shared Cluster.
Once you have selected the type of cluster, you’ll be able to choose from the top three cloud
providers (Amazon Web Services, Microsoft Azure, and Google Cloud Platform) and select a
region for hosting the cluster.
You’ll also be able to select the cluster tier and additional settings, such as turn on backup
and cluster name. Some options, such as the MongoDB version cloud backups, are only
available with the paid cluster tiers.
Once you are satisfied with your selection, click the Create Cluster button. It may take a
couple of minutes for Atlas to launch your cluster in the selected cloud hosting provider.
When the cluster is ready, you will see the cluster name with a green circle next to it,
indicating a successful setup. You will also see several metrics next to it indicating
connections, operations, and the size of your cluster.
In order to access your MongoDB Atlas cluster, you’ll need to enable network access for
your network or IP address and create a database user for connecting to the cluster. After that,
you can generate a connection string for your application or script.
For security reasons, new database clusters do not have network access enabled by default.
You need to enable network access explicitly by whitelisting the addresses that will connect
to the cluster.
Each entry can be an IP address, a subnet, or you can enable access from any location. In
general, you would grant access only to a list of subnets or IP addresses rather than grant
access to any location. This limits the connections your cluster accepts, making it more
secure.
To enable network access to your cluster, click on the Connect button from the clusters view
in the Atlas management console. This will open up the connection settings wizard.
In order to allow access from your current IP address, click on the Add your current IP
address button. If you need to access it from a different IP address or subnet, click on the Add
a different IP address button and enter the IP or a subnet using the CIDR notation, such as
172.10.1.0/24.
In order to connect to the database from a script or an application, you must first create a
MongoDB database user. The database user allows you to connect and use the databases.
Please note this is separate from the user that logs in and manages the clusters and resources
in Atlas.
Database users are created per project and have access to all the clusters in the project. You
can also assign different roles and privileges to the database users. Note that the first user you
create will automatically be granted administrative privileges.
Right below the network access settings, you can create a database user. First enter the
username and password and then click on the Create database user button.
If you later need to add more users to the project, you can do it from the Security tab.
Depending on your application, you may need to install a driver (library) corresponding to
your platform in order to connect to a cluster in Atlas. You can see the full list of supported
drivers here. If you’re using Compass (the MongoDB UI application) or the mongo
shell application, the drivers are already built in.
Regardless of your application, you’ll need to generate a database connection string for your
cluster. If you are just creating your cluster, the last step in the process will allow you to
create a connection string. Once you have enabled network access and created a database
user, you can click on the Choose connection method button, which will allow you to
generate a connection string for your application. You can also create the connection string
by clicking on the Connect button on your cluster from the Clusters tab in Atlas.
Click on the Connect your application button and then select the driver, such as Node.js,
Python, or another language. Then, select the version to generate the connection string for
your application. You can even check the "Include full driver code example" option in order
to generate the code to test the connectivity.
Note that the connection string generated does not include the actual cluster user login. You
will need to replace the <username> and <password> with your actual username and
password. You will also need to replace MyFirstDatabase with an actual database name in
your cluster.
Sample Data
If you are just starting with MongoDB, you may want to load a sample data set.
From the cluster view in the Atlas management console, click on the ellipsis button [...] and
select “Load Sample Data” from the menu. Then confirm your selection.
This will load a few sample collections that you can use to run test queries and learn more
about MongoDB. You can view the sample collections loaded by clicking on the Collections
button on your cluster from the Clusters tab in Atlas.
Conclusion
MongoDB Atlas is a great option for those who don’t have the time or resources to manage
all the infrastructure needed for a MongoDB cluster. You can have a cluster up and running
in minutes, allowing you to focus on your application instead of managing a database. And
with the free tier, it’s easy to start exploring.
Be sure to also check out the Atlas documentation and MongoDB University courses for
developers. They’re free and will provide you with more in-depth information about how to
use MongoDB with Java, Javascript, Python or C#/.Net.
Unit-5
Express.js
5.1.Express introduction
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.
Why Express ?
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.
Simple to interface with a variety of template engines, including Jade, Vash, and EJS.
Allows you to specify a middleware for handling errors.
5.2.Building blocks of express.js
7 building blocks of express.js
Server
App
Route
Router
Request
Response
Middeleware
5.3.What Is Middleware?
A request handler with access to the application's request-response cycle is known as
middleware.
It's a function that holds the request object, the response object, and the middleware
function.
Middleware can also send the response to the server before the request.
We can access and modify request and response data using middleware.
Functions of Middleware
We use these functions to modify our middleware to perform many tasks. If we want to block
our site for some country or if we're going to check the authentication of a user etc., we use
middleware for that.
Creating Middleware
Now we will create an Express middleware for that we will create a simple Express API. We
can create middleware in a router file, but the easiest method is to create a separate middleware
file and then execute it; creating and using middleware is very simple.
So to create middleware, we need to install all the packages to run express middleware.
Fig - app.js
Now open your terminal and run this file we will see our server is running.
After this, go to the local server and type localhost:4000
Now we will call our next parameter,
In express framework, next is a function
Fig - middleware
Create a file app.js, we will write the whole express code in that file. This will be our folder
structure. Now Inside app.js, Import express with require keyword and create an app by
calling the express() function provided by the express framework. Set the port for our local
application, 3000 is the default but you can choose any according to the availability of ports.
Call the listen() function, It requires path and callback as an argument. It starts listening to
the connection on the specified path, the default host is localhost, and our default path for the
local machine is the localhost:3000, here 3000 is the port which we have set earlier. The
callback function gets executed either on the successful start of the server or due to an error.
App.js
const express = require('express');
const app = express();
const PORT = 3000;
app.listen(PORT, (error) =>{
if(!error)
console.log("Server is Successfully Running,
and App is listening on port "+ PORT)
else
console.log("Error occurred, server can't start", error);
}
);
Step to run the application: Now as we have created a server we can successfully start
running it to see it’s working, write this command in your terminal to start the express
server.
node app.js
Output: You will see something like this on the terminal.
Now with all of this, we have created and run the server successfully, if your server is not
starting then there may be some error, try to analyze and read that error and resolve it
accordingly.
Finally, after a successful run if you try to open the URL (localhost:3000) on the browser it
will show you cannot GET / because we have not configured any route on this application
yet.
Step 4: Now we will set all the routes for our application.
Routes are the endpoints of the server, which are configured on our backend server and
whenever someone tries to access those endpoints they respond accordingly to their
definition at the backend. If you’re a beginner you can consider route as a function that get s
called when someone requests the special path associated with that function and return the
expected value as a response. We can create routes for HTTP methods like get, post, put,
and so on.
Syntax: The basic syntax of these types of routes looks like this, the given function will
execute when the path and the request method resemble.
app.anyMethod(path, function)
Example 1: Setting up a basic get request route on the root URL (‘/’ path) of the server.
1. With app.get() we are configuring our first route, it requires two arguments first one is
the path and, the second one is a function that will be executed when anyone requests
this path with GET method. The express provides the request and response object as a
parameter to all such types of functions.
2. The req is a giant object which will be received from the user and res is an object
which will be sent to the user after the function finishes execution.
3. Later we are calling status() method it takes an HTTP status code as an argument and
when the response is returned, the status will be sent along.
4. Finally, we are returning the response to the user. The send() method takes a string,
object, array, or buffer as an argument and is used to send the data object back to the
client as an HTTP response, also there are lots of types of response in express like
res.json() which is used to send JSON object, res.sendFile() which is used to send a file,
etc.
Express.js POST Request
GET and POST both are two common HTTP requests used for building REST API's. POST
requests are used to send large amount of data.
Express.js facilitates you to handle GET and POST requests using the instance of express.
Post method facilitates you to send large amount of data because data is send in the body. Post
method is secure because data is not visible in URL bar but it is not used as popularly as GET
method. On the other hand GET method is more efficient and used more than POST.
Index.html
1. <html>
2. <body>
3. <form action="http://127.0.0.1:8000/process_post" method="POST">
4. First Name: <input type="text" name="first_name"> <br>
5. Last Name: <input type="text" name="last_name">
6. <input type="submit" value="Submit">
7. </form>
8. </body>
9. </html>
Postex.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(express.static('public'));
app.get('/index.html', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
app.post('/process_post', urlencodedParser, function (req, res) {
// Prepare output in JSON format
response = {
first_name:req.body.first_name,
last_name:req.body.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
var server = app.listen(8000, function () {
var host = server.address().address
var port = server.address().port
5.5.express-jade
Jade is a template engine for Node.js. Jade syntax is easy to learn. It uses whitespace and
indentation as a part of the syntax.
Jade template must be written inside .jade file. And all .jade files must be put
inside views folder in the root folder of Node.js application.
Note:
By default Express.js searches all the views in the views folder under the root
folder, which can be set to another folder using views property in express e.g.
app.set('views','MyViews').
Sample.jade
doctype html
html
head
title Jade Page
body
h1 This page is produced by Jade engine
p some paragraph here..
<!DOCTYPE html>
<html>
<head>
<title>Jade Page</title>
</head>
<body>
<h1>This page is produced by Jade engine</h1>
<p>some paragraph here..</p>
</body>
</html>
Server.js
var express = require('express');
var app = express();
res.render('sample');
});
Changes to this layer should not affect the entities. Changes to externalities such as the
database, user interface, or frameworks are unlikely to affect this layer.
3. Interface Adapters
The Interface Adapters or the Adapter layer holds the controllers, APIs, and gateways. The
Interface Adapters govern the flow of communication between external components and the
system's back-end.
In simple words, Interface Adapters are isolating our various Use Cases from the tools
that we use.
4. Routes
The /routes folder is where you can organize all of your different REST endpoints
declarations. The file below exposes all available endpoints related to the Orders Entity:
Web frameworks provide resources such as HTML pages, scripts, images, etc. at different
routes.
app.method(path, handler)
This METHOD can be applied to any one of the HTTP verbs – get, set, put, delete. An alternate
method also exists, which executes independent of the request type.
Handler is a callback function that executes when a matching request type is found on the
relevant route. For example,
app.listen(3000);
If we run our application and go to localhost:3000/hello, the server receives a get request
at route "/hello", our Express app executes the callback function attached to this route and
sends "Hello World!" as the response.
11
ExpressJS
We can also have multiple different methods at the same route. For example,
app.listen(3000);
To test this request, open up your terminal and use cURL to execute the following request:
A special method, all, is provided by Express to handle all types of http methods at a
particular route using the same function. To use this method, try the following.
This method is generally used for defining middleware, which we'll discuss in the middleware
chapter.
Routers
Defining routes like above is very tedious to maintain. To separate the routes from our main
index.js file, we will use Express.Router. Create a new file called things.js and type the
following in it.
Now to use this router in our index.js, type in the following before the app.listen function
call.
app.listen(3000);
The app.use function call on route '/things' attaches the things router with this route. Now
whatever requests our app gets at the '/things', will be handled by our things.js router. The
'/' route in things.js is actually a subroute of '/things'. Visit localhost:3000/things/ and you
will see the following output.
13
ExpressJS
Routers are very helpful in separating concerns and keep relevant portions of our code
together. They help in building maintainable code. You should define your routes relating to
an entity in a single file and include it using the above method in your index.js file.
14
EXPRESSJS – HTTP METHODS ExpressJS
The HTTP method is supplied in the request and specifies the operation that the client has
requested. The following table lists the most used HTTP methods:
Method Description
The POST method requests that the server accept the data enclosed in the
POST
request as a new object/entity of the resource identified by the URI.
The PUT method requests that the server accept the data enclosed in the
PUT request as a modification to existing object identified by the URI. If it does not
exist then the PUT method should create one.
DELETE The DELETE method requests that the server delete the specified resource.
These are the most common HTTP methods. To learn more about the methods,
visit http://www.tutorialspoint.com/http/http_methods.htm.
15
ANGULAR
Unit-6
AngularJS
6.1.AngularJS Introduction:
AngularJS is a very powerful JavaScript Framework. It is used in Single Page Application
(SPA) projects. It extends HTML DOM with additional attributes and makes it more
responsive to user actions. AngularJS is open source, completely free, and used by thousands
of developers around the world. It is licensed under the Apache license version 2.0.
<html>
<head>
<title>AngularJS First Application</title>
</head>
<body>
<h1>Sample Application</h1>
</body>
</html>
Overall, AngularJS is a framework to build large scale, high-performance, and easyto-maintain
web applications.
SPA frameworks have been steadily gaining popularity, especially for businesses and
startups. There are many advantages using single page application framework in your web
project-
EmberJS
ReactJS is a JavaScript library of UI components used for designing an interactive web app
interface. This library is often confused for a client-side framework because of the vast array
of features it offers.
BackBoneJS
Vue
Vue is a popular progressive JavaScript framework used for developing high-performing web
applications and web interfaces.
6.4.MVC ARCHITECTURE
The Model
The model is responsible for managing application data. It responds to the request from view
and to the instructions from controller to update itself.
The View
The Controller
The controller responds to user input and performs interactions on the data model objects. The
controller receives input, validates it, and then performs business operations that modify the
state of the data model.
AngularJS is a MVC based framework.
6.5.Getting Angular:
Installation Process of Angular CLI
To install the Angular CLI on your machine, open the terminal window and run the
following command:
where -g denotes that CLI is being installed globally to your machine, which means you can
create or run any command of CLI anywhere on your machine. Once you run the above
command CLI will be installed on your machine, and you can verify the version installed
using the following command:
ng version
Creating a Project using Angular CLI
Now, let’s create our first ever Angular project using Angular CLI. Open your terminal
window and type the command below on your machine.
ng new hello-world
After running this command you will find the full architecture of the project in the directory
where you run this command. The project folder will be something like below in the image
-
Run the following command on the terminal (Navigate to the project directory if you are not
in that directory).
ng serve
(or)or
ng serve --open
The --open (or just -o) option automatically opens your browser to
http://localhost:4200/. Accessing Angular Web Interface
ng serve command may take a few seconds to run your application, and once completed,
you should see a web page similar to the following.
<html>
<head>
<title>AngularJS First Application</title>
</head>
<body>
<h1>Sample Application</h1>
</body>
</html>
Output
Open the file testAngularJS.htm in a web browser. Enter your name and see the result.
6.6.DIRECTIVES
Directive Description
ng-bind Replaces the value of HTML control with the value of specified AngularJS expression.
ng-repeat Repeats HTML template once per each item in the specified collection.
6.7. controller
1. AngularJS controllers control the data of AngularJS applications.
Data binding in AngularJS is the synchronization between the model and the
view.
When data in the model changes, the view reflects the change, and when
data in the view changes, the model is updated as well. This happens
immediately and automatically, which makes sure that the model and the
view is updated at all times.
6.10.Testing Angular:
Testing your Angular application helps you check that your application is working as you expect.
Prerequisites
Before writing tests for your Angular application, you should have a basic understanding of the
following concepts:
Angular fundamentals
JavaScript
HTML
CSS
Angular CLI
Set up testing
The Angular CLI downloads and installs everything you need to test an Angular application
with Jasmine testing framework.
The project you create with the CLI is immediately ready to test. Just run the ng test CLI
command:
ng test
The ng test command builds the application in watch mode, and launches the Karma test
runner.
The test output is displayed in the browser using Karma Jasmine HTML Reporter