Unit-3-Fsd-Iv-I Cse
Unit-3-Fsd-Iv-I Cse
Unit-3-Fsd-Iv-I Cse
REACT JS: Introduction to React React Router and Single Page Applications ReactForms, Flow
Architecture and Introduction to Redux More Redux and Client- Server Communication
Introduction to React
ReactJS is a simple, feature rich, component based JavaScript UI library. It can be used to develop
small applications as well as big, complex applications. ReactJS provides minimal and solid feature set
to kick-start a web application. React community compliments React library by providing large set of
ready-made components to develop web application in a record time. React community also provides
advanced concept like state management, routing, etc., on top of the React library.
There are various reasons why you should choose ReactJS as a primary tool for website UI
development. Here, we highlight the most notable ones and explain why these specifics are so
important:
Fast - Feel quick and responsive through the Apps made in React can handle complex updates.
Modular - Allow you to write many smaller, reusable files instead of writing large, dense files of
code. The modularity of React is an attractive solution for JavaScript's visibility issues.
Scalable - React performs best in the case of large programs that display a lot of data changes.
Flexible - React approaches differently by breaking them into components while building user
interfaces. This is incredibly important in large applications.
Popular - ReactJS gives better performance than other JavaScript languages due to t’s
implementation of a virtual DOM.
Easy to learn - Since it requires minimal understanding of HTML and JavaScript, the learning
curve is low.
Server-side rendering and SEO friendly - ReactJS websites are famous for their server-side
rendering feature. It makes apps faster and much better for search engine ranking in comparison to
products with client-side rendering. React even produces more opportunities for website SEO and
can occupy higher positions on the search result’s page.
Reusable UI components - React improves development and debugging processes.
Community - The number of tools and extensions available for ReactJS developers is
tremendous. Along with impressive out-of-box functionalities, more opportunities emerge once
you discover how giant the React galaxy is. React has a vibrant community and is supported by
Facebook. Hence, it’s a reliable tool for website development.
ReactJS Features:
Debugging
Testing React apps is easy due to large community support. Even Facebook provides a small
browser extension that makes React debugging easier and faster.
Next, let’s understand some essential concepts of ReactJS.
ReactJS Components
Components are the heart and soul of React. Components (like JavaScript functions) let you split
the UI into independent, reusable pieces and think about each piece in isolation.
Components are building blocks of any React application. Every component has its structures,
APIs, and methods.
In React, there are two types of components, namely stateless functional and stateful1 class.
Functional Components or Stateless - These components have no state of their own and contain
only a render method. They are simply Javascript functions that may or may not receive data as
parameters.
Stateless functional components may derive data from other components as properties (props). An
example of repre
function WelcomeMessage(props) {
Class Components or Statefull- These components are more complex than functional
components. They can manage their state and to return JSX on the screen have a separate render
method. You can pass data from one class to other class components.
An example of representing class component is shown below:
render() {
return (
);
React State
A state is a place from where the data comes. The state in a component can change over time, and
whenever it changes, the component re-renders.
A change in a state can happen as a response to system-generated events or user action, and these
changes define the component’s behavior and how it will render.
};
updateName() {
React Props
React keys
In react, keys are useful when working with dynamically created components. Setting the key value
will keep your component uniquely identified after the change.
They help react in identifying the items which have changed, are removed, or added.
In summary, state, props, keys, and components are the few fundamental react concepts that you need
to be familiar with before working on it.
<div id="mydiv"></div>
<script type="text/babel">
function Hello() {
return <h1>Hello World!</h1>;
}
This way of using React can be OK for testing purposes, but for production you will need to set up
a React environment.
Routing is a process in which a user is directed to different pages based on their action or
request. ReactJS Router is mainly used for developing Single Page Web Applications.
React Router is used to define multiple routes in the application. When a user types a
specific URL into the browser, and if this URL path matches any 'route' inside the router
file, the user will be redirected to that particular route.
React Router is a standard library system built on top of the React and used to create
routing in the React application using React Router Package. It provides the synchronous
URL on the browser with data that will be displayed on the web page. It maintains the
standard structure and behavior of the application and mainly used for developing single
page web applications.
React Router plays an important role to display multiple views in a single page application.
Without React Router, it is not possible to display multiple views in React applications.
Most of the social media websites like Facebook, Instagram uses React Router for
rendering multiple views.
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.
It is not possible to install react-router directly in your application. To use react routing,
first, you need to install react-router-dom modules in your application. The below command
is used to install react router dom.
Example
Step-1: In our project, we will create two more components along with App.js, which is
already present.
About.js
It is not possible to install react-router directly in your application. To use react routing,
first, you need to install react-router-dom modules in your application. The below
command is used to install react router dom.
Example
Step-1: In our project, we will create two more components along with App.js, which is
already present.
About.js
It is not possible to install react-router directly in your application. To use react routing,
first, you need to install react-router-dom modules in your application. The below
command is used to install react router dom.
Example
Step-1: In our project, we will create two more components along with App.js, which is
already present.
About.js
import React from 'react'
class About extends React.Component {
render() {
return <h1>About</h1>
}
}
export default About
Contact.js
}
}
export default Contact
App.js
Step-2: For Routing, open the index.js file and import all the three component files in it.
Here, you need to import line: import { Route, Link, BrowserRouter as Router }
from 'react- router-dom' which helps us to implement the Routing. Now, our index.js
file looks like below.
What is Route?
It is used to define and render component based on the specified path. It will accept
components and render to define what should be rendered.
Index.js
<div>
</div>
</Router>
)
ReactDOM.render(routing, document.getElementById('root'));
Step-3: Open command prompt, go to your project location, and then type npm start.
You willget the following screen.
Now, if you enter manually in the browser: localhost:3000/about, you will see About
component is rendered on the screen
Step-4: In the above screen, you can see that Home component is still rendered.
It is because the home path is '/' and about path is '/about', so you can observe
that slash is common in both paths which render both components. To stop this
behavior, you need to use the exact prop. It can be seen in the below example.
Index.js
const routing = (
<Router>
<div>
</div>
</Router>
)
ReactDOM.render(routing, document.getElementById('root'));
Output
This component is used to create links which allow to navigate on different URLs and
render its content without reloading the webpage.
Example
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
<Router>
<div>
Output
Now, we need to add some styles to the Link. So that when we click on any particular
link, it can be easily identified which Link is active. To do this react router provides a
new trick NavLink instead of Link. Now, in the index.js file, replace Link from Navlink
and add properties activeStyle. The activeStyle properties mean when we click on the
Link, it should have a specific style so that we can differentiate which one is currently
active.
<Router>
<div>
<h1>React Router Example</h1>
<ul>
<li>
<NavLink to="/" exact activeStyle={
{color:'red'}
}>Home</NavLink>
</li>
<li>
<NavLink to="/about" exact activeStyle={
{color:'green'}
}>About</NavLink>
</li>
<li>
<NavLink to="/contact" exact activeStyle={
{color:'magenta'}
}>Contact</NavLink>
</li>
</ul>
ReactDOM.render(routing, document.getElementById('root'));
Output
When we execute the above program, we will get the following screen in which we can see that
Home link is of color Red and is the only currently active link.
<Link> vs <NavLink>
The Link component allows navigating the different routes on the websites, whereas
NavLink component is used to add styles to the active routes.
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.
Uncontrolled component
Controlled component
Example:
1) import React from 'react';
2) import ReactDOM from 'react-dom/client';
3)
4) function MyForm() {
5) return (
6) <form>
7) <label>Enter your name:
8) <input type="text" />
9) </label>
10) </form>
11) )
12) }
13)
14) const root = ReactDOM.createRoot(document.getElementById('root'));
15) root.render(<MyForm />);
This will work as normal, the form will submit and the page will refresh.
But this is generally not what we want to happen in React.
We want to prevent this default behavior and let React control the form.
Handling Forms
Handling forms is about how you handle the data when it changes value or gets submitted.
In HTML, form data is usually handled by the DOM.
In React, form data is usually handled by the components.
When the data is handled by the components, all the data is stored in the component state.
You can control changes by adding event handlers in the onChange attribute.
We can use the useState Hook to keep track of each inputs value and provide a "single source of
truth" for the entire application.
Example:
Submitting Forms
You can control the submit action by adding an event handler in the onSubmit attribute for the <form>:
Example:
Add a submit button and an event handler in the onSubmit attribute:
1. import { useState } from 'react';
2. import ReactDOM from 'react-dom/client';
3. function MyForm() {
4. const [name, setName] = useState("");
5. const handleSubmit = (event) => {
6. event.preventDefault();
7. alert(`The name you entered was: ${name}`)
8. }
9. return (
10. <form onSubmit={handleSubmit}>
11. <label>Enter your name:
12. <input
13. type="text"
14. value={name}
15. onChange={(e) => setName(e.target.value)}
16. />
17. </label>
18. <input type="submit" />
19. </form>
20. )
21. }
Example:
Write a form with two input fields:
1. import { useState } from 'react';
2. import ReactDOM from 'react-dom/client';
3. function MyForm() {
4. const [inputs, setInputs] = useState({});
5. const handleChange = (event) => {
6. const name = event.target.name;
7. const value = event.target.value;
8. setInputs(values => ({...values, [name]: value}))
9. }
10. const handleSubmit = (event) => {
11. event.preventDefault();
12. alert(inputs);
13. }
14. return (
15. <form onSubmit={handleSubmit}>
16. <label>Enter your name:
17. <input
18. type="text"
19. name="username"
20. value={inputs.username || ""}
21. onChange={handleChange}
22. />
23. </label>
24. <label>Enter your age:
25. <input
26. type="number"
27. name="age"
28. value={inputs.age || ""}
29. onChange={handleChange}
30. />
31. </label>
32. <input type="submit" />
33. </form>
34. )
35. }
Textarea
The textarea element in React is slightly different from ordinary HTML.
In HTML the value of a textarea was the text between the start tag <textarea> and the end
tag </textarea>.
1. <textarea>
2. Content of the textarea.
3. </textarea>
In React the value of a textarea is placed in a value attribute. We'll use the useState Hook to manage the
value of the textarea:
Example:
A simple textarea with some content:
1. import { useState } from 'react';
2. import ReactDOM from 'react-dom/client';
3. function MyForm() {
4. const [textarea, setTextarea] = useState(
5. "The content of a textarea goes in the value attribute"
6. );
10. return (
11. <form>
12. <textarea value={textarea} onChange={handleChange} />
13. </form>
14. )
15. }
Select
A drop down list, or a select box, in React is also a bit different from HTML.
in HTML, the selected value in the drop down list was defined with the selected attribute:
HTML:
1. <select>
2. <option value="Ford">Ford</option>
3. <option value="Volvo" selected>Volvo</option>
4. <option value="Fiat">Fiat</option>
5. </select>
In React, the selected value is defined with a value attribute on the select tag:
Example:
A simple select box, where the selected value "Volvo" is initialized in the constructor:
1. function MyForm() {
2. const [myCar, setMyCar] = useState("Volvo");
3. const handleChange = (event) => {
4. setMyCar(event.target.value)
5. }
6. return (
7. <form>
8. <select value={myCar} onChange={handleChange}>
9. <option value="Ford">Ford</option>
10. <option value="Volvo">Volvo</option>
11. <option value="Fiat">Fiat</option>
12. </select>
13. </form>
14. )
15. }
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.
27. }
28. export default App;
Output
Architecture of the React Application
React library is just UI library and it does not enforce any particular pattern to write a
complex application. Developers are free to choose the design pattern of their choice. React
community advocates certain design pattern. One of the patterns is Flux pattern. React
library also provides lot of concepts like Higher Order component, Context, Render props,
Refs etc., to write better code. React Hooks is evolving concept to do state management in
big projects. Let us try to understand the high level architecture of a React application.
● React app starts with a single root component.
● Root component is build using one or more component.
● Each component can be nested with other component to any level.
● Composition is one of the core concepts of React library. So,
each component is build by composing smaller components
instead of inheriting one component from another component.
● Most of the components are user interface components.
● React app can include third party component for specific
purpose such as routing, animation, state management,
etc.
React Redux
Redux is an open-source JavaScript library used to manage application state. React uses
Redux for building the user interface. It was first introduced by Dan Abramov and Andrew
Clark in 2015.
React Redux is the official React binding for Redux. It allows React components to read
data from a Redux Store, and dispatch Actions to the Store to update data. Redux helps
apps to scale by providing a sensible way to manage state through a unidirectional data flow
model. React Redux is conceptually simple. It subscribes to the Redux store, checks to see if
the data which your component wants have changed, and re-renders your component.
Redux was inspired by Flux. Redux studied the Flux architecture and omitted unnecessary
complexity.
● Redux does not have Dispatcher concept.
● Redux has an only Store whereas Flux has many Stores.
● The Action objects will be received and handled directly by Store.
Redux Architecture
Store − The central place to store the state of the application.
Actions − Action is an plain object with the type of the action to be done and the input (called payload)
necessary to do the action. For example, action for adding an item in the store contains ADD_ITEM as
type and an object with item's details as payload. The action can be represented as −
1. {
2. type: 'ADD_ITEM',
4. }
Reducers − Reducers are pure functions used to create a new state based on the existing state and the
current action. It returns the newly created state. For example, in add item scenario, it creates a new
item list and merges the item from the state and new item and returns the newly created list.
Action creators − Action creator creates an action with proper action type and data necessary for the
action and returns the action. For example, addItem action creator returns below object −
1. {
2. type: 'ADD_ITEM',
4. }
Component − Component can connect to the store to get the current state and dispatch action to the
store so that the store executes the action and updates it's current state.
To change the state, React component creates necessary action and dispatches the action.
Reducer creates a new state based on the action and returns it. Store updates itself with the new state.
Once the state changes, store sends the updated state to all its subscribed component.
Redux API
Redux provides a single api, connect which will connect a components to the store and allows the
component to get and set the state of the store.
All parameters are optional and it returns a HOC (higher order component). A higher order component
is a function which wraps a component and returns a new component.
Let us see the first two parameters which will be enough for most cases.
Provider component
React Redux provides a Provider component and its sole purpose to make the Redux store available to
its all nested components connected to store using connect API. The sample code is given below −
1. import React from 'react'
2. import ReactDOM from 'react-dom'
3. import { Provider } from 'react-redux'
4. import { App } from './App'
5. import createStore from './createReduxStore'
Working example
Let us recreate our expense manager application and uses the React redux concept to maintain the state
of the application.
First, create a new react application, react-message-app using Create React App or Rollup bundler by
following instruction in Creating a React application chapter.
Next, install uuid library to generate unique identifier for new expenses.
Next, create src folder under the root directory of the application.
Next, create a file, types.js under src/actions folder and start editing.
Next, add two action type, one for add expense and one for remove expense.
Next, create a file, index.js under src/actions folder to add action and start editing.
Here, the function expects expense object and return action type of ADD_EXPENSE along with a
payload of expense information.
Next, add a new function to return action type for deleting an expense and export it.
Here, the function expects id of the expense item to be deleted and return action type of
'DELETE_EXPENSE' along with a payload of expense id.
Next, create a file, index.js under src/reducers to write reducer function and start editing.
Next, add a function, expensesReducer to do the actual feature of adding and updating expenses in the
redux store.
Here, the reducer checks the action type and execute the relevant code.
Next, create a file, ExpenseEntryItemList.css under src/components folder and add generic style for the
html tables.
html {
font-family: sans-serif;
}
table {
border-collapse: collapse;
border: 2px solid rgb(200,200,200);
letter-spacing: 1px;
font-size: 0.8rem;
}
td, th {
border: 1px solid rgb(190,190,190);
padding: 10px 20px;
}
th {
background-color: rgb(235,235,235);
}
td, th {
text-align: left;
}
tr:nth-child(even) td {
background-color: rgb(250,250,250);
}
tr:nth-child(odd) td {
background-color: rgb(245,245,245);
}
caption {
padding: 10px;
}
tr.highlight td {
background-color: #a6a8bd;
}
Next, create a file, ExpenseEntryItemList.js under src/components folder and start editing.
import './ExpenseEntryItemList.css';
Here, we created two function, one to dispatch add expense (addExpense) function and another to
dispatch delete expense (deleteExpense) function and mapped those function to props of the
component.
Next, add few expense into the redux store in the constructor using onAddExpense property.
if (this.props.expenses.length == 0)
{
const items = [
{ id: 1, name: "Pizza", amount: 80, spendDate: "2020-10-10", category: "Food" },
{ id: 2, name: "Grape Juice", amount: 30, spendDate: "2020-10-12", category: "Food" },
{ id: 3, name: "Cinema", amount: 210, spendDate: "2020-10-16", category: "Entertainment" },
{ id: 4, name: "Java Programming book", amount: 242, spendDate: "2020-10-15", category:
"Academic" },
{ id: 5, name: "Mango Juice", amount: 35, spendDate: "2020-10-16", category: "Food" },
{ id: 6, name: "Dress", amount: 2000, spendDate: "2020-10-25", category: "Cloth" },
{ id: 7, name: "Tour", amount: 2555, spendDate: "2020-10-29", category: "Entertainment" },
{ id: 8, name: "Meals", amount: 300, spendDate: "2020-10-30", category: "Food" },
{ id: 9, name: "Mobile", amount: 3500, spendDate: "2020-11-02", category: "Gadgets" },
{ id: 10, name: "Exam Fees", amount: 1245, spendDate: "2020-11-04", category: "Academic" }
]
items.forEach((item) => {
this.props.onAddExpense(
{
name: item.name,
amount: item.amount,
spendDate: item.spendDate,
category: item.category
}
);
})
}
Next, add an event handler to delete the expense item using expense id.
Here, the event handler calls the onDelete dispatcher, which call deleteExpense along with the
expense id.
getTotal() {
let total = 0;
for (var i = 0; i < this.props.expenses.length; i++) {
total += this.props.expenses[i].amount
}
return total;
}
Next, add render() method and list the expense item in the tabular format.
render() {
const lists = this.props.expenses.map(
(item) =>
<tr key={item.id}>
<td>{item.name}</td>
<td>{item.amount}</td>
<td>{new Date(item.spendDate).toDateString()}</td>
<td>{item.category}</td>
<td><a href="#"
onClick={(e) => this.handleDelete(item.id, e)}>Remove</a></td>
</tr>
);
return (
<div>
<table>
<thead>
<tr>
<th>Item</th>
<th>Amount</th>
<th>Date</th>
<th>Category</th>
<th>Remove</th>
</tr>
</thead>
<tbody>
{lists}
<tr>
<td colSpan="1" style={{ textAlign: "right" }}>Total Amount</td>
<td colSpan="4" style={{ textAlign: "left" }}>
{this.getTotal()}
</td>
</tr>
</tbody>
</table>
</div>
);
}
Here, we set the event handler handleDelete to remove the expense from the store.
if (this.props.expenses.length == 0){
const items = [
{ id: 1, name: "Pizza", amount: 80, spendDate: "2020-10-10", category: "Food" },
{ id: 2, name: "Grape Juice", amount: 30, spendDate: "2020-10-12", category: "Food" },
{ id: 3, name: "Cinema", amount: 210, spendDate: "2020-10-16", category: "Entertainment" },
{ id: 4, name: "Java Programming book", amount: 242, spendDate: "2020-10-15", category:
"Academic" },
{ id: 5, name: "Mango Juice", amount: 35, spendDate: "2020-10-16", category: "Food" },
{ id: 6, name: "Dress", amount: 2000, spendDate: "2020-10-25", category: "Cloth" },
{ id: 7, name: "Tour", amount: 2555, spendDate: "2020-10-29", category: "Entertainment" },
{ id: 8, name: "Meals", amount: 300, spendDate: "2020-10-30", category: "Food" },
{ id: 9, name: "Mobile", amount: 3500, spendDate: "2020-11-02", category: "Gadgets" },
{ id: 10, name: "Exam Fees", amount: 1245, spendDate: "2020-11-04", category: "Academic" }
]
items.forEach((item) => {
this.props.onAddExpense(
{
name: item.name,
amount: item.amount,
spendDate: item.spendDate,
category: item.category
}
);
})
}
}
handleDelete = (id,e) => {
e.preventDefault();
this.props.onDelete(id);
}
getTotal() {
let total = 0;
for (var i = 0; i < this.props.expenses.length; i++) {
total += this.props.expenses[i].amount
}
return total;
}
render() {
const lists = this.props.expenses.map((item) =>
<tr key={item.id}>
<td>{item.name}</td>
<td>{item.amount}</td>
<td>{new Date(item.spendDate).toDateString()}</td>
<td>{item.category}</td>
<td><a href="#"
onClick={(e) => this.handleDelete(item.id, e)}>Remove</a></td>
</tr>
);
return (
<div>
<table>
<thead>
<tr>
<th>Item</th>
<th>Amount</th>
<th>Date</th>
<th>Category</th>
<th>Remove</th>
</tr>
</thead>
<tbody>
{lists}
<tr>
<td colSpan="1" style={{ textAlign: "right" }}>Total Amount</td>
<td colSpan="4" style={{ textAlign: "left" }}>
{this.getTotal()}
</td>
</tr>
</tbody>
</table>
</div>
);
}
}
const mapStateToProps = state => {
return {
expenses: state
};
};
const mapDispatchToProps = dispatch => {
return {
onAddExpense: expense => {
dispatch(addExpense(expense));
},
onDelete: id => {
dispatch(deleteExpense(id));
}
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(ExpenseEntryItemList);
Next, create a file, App.js under the src/components folder and use ExpenseEntryItemList component.
Here,
Finally, create a public folder under the root folder and create index.html file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>React Containment App</title>
</head>
<body>
<div id="root"></div>
<script type="text/JavaScript" src="./index.js"></script>
</body>
</html>
Next, serve the application using npm command.
npm start
Next, open the browser and enter http://localhost:3000 in the address bar and press enter.
Clicking the remove link will remove the item from redux store.
HTTP & Client-Server Communication
Hypertext Transfer Protocol (HTTP) is the protocol that web browsers and web servers use "under the
hood" to communicate with each other over the Internet. It is text based. HTTP is a protocol which
allows the fetching of resources, such as HTML documents. After the request is serviced by a server,
the connection between client and server across the Internet is disconnected. A new connection must be
made for each request. Most protocols are connection oriented, where the connection is kept open over
the Internet. HTTP does not however. Before an HTTP request can be made by a client, a new
connection must be made to the server.
Clients and servers communicate by exchanging individual messages (as opposed to a stream of data).
The messages sent by the client, usually a Web browser, are called requests and the messages sent by
the server as an answer are called responses. A request is made by an entity called a user-agent, which
is typically a web browser however can be a bot or scraper. The server answer with a response. In
between can be any number of proxies or caches that can act as gateways.
HTTP is stateless, which means inherently data isn’t saved. HTTP cookies allow use of stateful
sessions. This might be used for example with an e-commerce website as you click from page to page.
HTTP Request
● Body
● Headers
● Query strings
● HTTP version
● Headers
An HTTP method, usually a verb like GET, POST or a noun like OPTIONS or HEAD that
defines the operation the client wants to perform. Typically, a client wants to fetch a resource
(using GET) or post the value of an HTML form (using POST), though more operations may be
needed in other cases.
The path of the resource to fetch; the URL of the resource stripped from elements that are
obvious from the context, for example without the protocol (http://), the domain
(here, developer.mozilla.org), or the TCP port (here, 80).
The version of the HTTP protocol.
Optional headers that convey additional information for the servers.
Or a body, for some methods like POST, similar to those in responses, which contain the
resource sent.
Now that we know what HTTP is and why it’s used, let’s talk about the
different methods we have available to us.
In the weather app example above, we wanted to retrieve weather information
about a city. But what if we wanted to submit weather information for a city?
In real life, you probably wouldn’t have permissions to alter someone else’s data,
but let’s imagine that we are contributors to a community-run weather app. And in
addition to getting the weather information from an API, members in that city could
update this information to display more accurate data.
We use POSTto create a new resource. A POSTrequest requires a body in which you
define the data of the entity to be created.
A successful POST request would be a 200 response code. In our weather
app, we could use a POST method to add weather data about a new city.
We use PUT to modify a resource. PUT updates the entire resource with data that is
passed in the body payload. If there is no resource that matches the request, it will
create a new resource.
In our weather app, we could use PUTto update all weather data about a
specific city.
We use PATCHto modify a part of a resource. With PATCH, you only need to pass
in the data that you want to update.
In our weather app, we could use PATCHto update the rainfall for a specified day in
a specified city.
HTTP DELETE request
There are many different ways how to structure a web application. The frontend can take
different forms, and it can be daunting to understand how to connect the two.
This article is an overview of what goes on between the backend and the frontend of a web
application - how the two communicate.
Let’s start with fundamentals.
The backend and frontend both work together to serve a single goal. It’s pretty helpful to keep it in
mind at all times. They are made, so a user can access them. In detail this interaction can look like
this:
The front- and backend make this possible by causing requests to be sent and answering with
responses.
Before diving deeper, we should make sure we’re talking about the same things.
Definitions
To make sure that we are on the same page, here are descriptions of possible ambiguous “big words” in
this article:
Server - the abstract “thing” where the browser’s requests arrive. We don’t care about that detail to
much here. It’s enough to know that the backend code is running on the server as well as other services.
Request for the backend arrive at the server and are eventually passed on to your backend code.
Backend - the part of your web app which is not directly visible to the user. It receives requests and
prepares data which is transmitted back to the user’s browser. Backend code is built to be running on a
server and it’s never running on the user’s machine.
Frontend - the parts of your web application which are intended to be used directly by the the user’s
browser. Code which is executed inside the browser, or markup which is interpreted while rendering a
page. HTML, CSS and in-browser JavaScript are good examples for what I would consider to be part
of the frontend concept. But only in their finished form. While the backend code can be assembling a
HTML response, the final HTML arriving in the browser is meant here.
Browser - an application running on the user’s device. It sends out HTTP requests, receives responses,
processes the received data, and uses it to render a viewable page. All of communication from the
user’s side goes through their browser.
HTTP requests arrive from the browser at the backend. Those requests may contain data in the HTTP
headers or request body. The intent may be to request new data or to transmit user-created data to the
backend.
HTTP requests, are constructed inside the user’s browser and sent off. There’s a response for each
request, carrying information in the HTTP headers and the request body. Those responses arrive back
at the backend arrive back at the user’s browser.
What needs to happen, to make the browser have to send out a request? Those requests which are fired
because a user clicked a link or by JS code running in the background. But there are more possible
triggers:
The user enters a URL, which makes the browser go and request it.
The browser reads the incoming HTML, and notices that there’s a resource it needs to load, such
as a JS file, an image or a CSS file. It goes ahead and requests each with a single new HTTP
request. Usually this happens while loading a website. (Those requests don’t have to go to the
same backend, you could load JS from another site. People like to use CDNs for that as it’s pretty
fast and convenient.)
A user clicks on a plain-ol’ link the webpage is loaded and rendered. The browser knows that they
need to navigate to a new page and requests the corresponding URL.
JavaScript is executed on the site, and wants to have some data loaded in the background. Requests
are being made, but the browser does that in the background. It doesn’t reload the whole page.
That’s AJAX. Javascript can be triggered by a user clicking something, and it can tell the browser
that the click wasn’t meant to navigate to a new page. This can be confusing.
That’s pretty much all scenarios which can make a browser fire off requests to the backend. In each
case, there are HTTP requests and responses involved.
This one can differ! But there’s a very popular way of doing things, which is used most often. It’s a
good way of doing things for 99% of all frontend-backend communication scenarios.
The magic is within the HTTP request/response payloads. The backend usually responds with certain
contents of the HTTP body:
HTML-formatted responses
other static files (CSS, JS, images, …)
JSON-formatted data
No body at all. Just a status code and header fields.