A bit into history, in the olden days the working of simple websites such as message displayers and random calculators used to be so different.
The web page sends the data to the server, and all the logic and computation happens at the server, and then the server sends the data back to the client(browser), and the result gets displayed on the web page.
This, indeed, is hefty and time-consuming for very simple websites that hardly used any functionality, which slows down the performance of the website.
What is a website?
A page that displays some content on any kind of browser is known as a web page. A web page is set up using a markup language, generally HTML(Hyper Text Markup Language).
A website is simply a collection of one or many web pages under a common domain name. There are two types of websites, static and dynamic.
Static vs Dynamic website
A website is called static if the data it displays is fixed and cannot be changed. Static websites contain text content and attached images, links to external sites, and no buttons, forms, or dynamic/interactive content.
But there are also a vast majority of websites that allow the user to change or manipulate the data displayed on the browser. They are called Dynamic/Responsive websites.
Calculators, Unit Convertors, Message displayers, etc are some simple examples of responsive websites. Much complex ones may include applications like online food order and delivery which allows the user to access the features only if he/she is authorized.
Basically, there are two parts/ so-called ends for every website which when put together forms a complete web application.
Briefly, front-end refers to the client-side or web design in the web industry. Back-end refers to the server-side.
Add the following code inside the scriptlet tag – alert(“Hello world!”);
The code looks something like this-
<!DOCTYPE html> <html lang="en" dir="ltr">
</body> <script> alert(“Hello World”); </script>
Now let’s add some behaviour, let us store the data provided inside the dialogue box (say our name) inside a variable and use it to display a message with our name. For that add the following code inside the scriptlet tag-
var name = prompt(“What is your name”); alert(“Hello ”+name+”!”);
Hola! Now that we have seen how to add JS to a website, let us dive deep and set up a dynamic website using JS. The application that we are going to build is a simple online calculator performing basic operations of Addition, Subtraction, Multiplication, and Division.
Setting up the Backend requirements
Node.js allows us to take JS out of the browser and allows it to interact directly with the hardware of the computer.
Let us see how we can install it – Download the installer from nodejs , choose the LTS version. Now run the installer(.msi file) and accept all the default options. Restart your computer.
Node Package Manager and Express framework for backend
Express is a very popular framework for Node that many people depend on, it reduces the code by almost 5-10 times. Also, many packages that are used in the Node also depend on Express to run.
NPM(Node Package Manager) is a package manager for external modules. NPM will be installed along with the node on our system.
Create a folder named Calculator with three files inside, index.html, style.css, and app.js.
Now, open the command prompt and navigate to the required directory, and follow these steps with explanation in parentheses-
Open the command prompt and run the command, “npm init” to initialize npm, and accept all default options.
Run the command “npm i express body-parser”, to install packages express and body-parser.
Open the project inside any text editor you choose.
Note: create a folder named “public” inside the project, and a folder “css” inside the public folder, and move style.css inside that folder.
Here goes the code for index.html, this adds the structure for the calculator.
<meta charset="utf-8"> <link rel="stylesheet" href="/css/style.css"> <title>Calculator</title>
<h1>Calculator</h1> <form class="formclass" action="/" method="post"> <label for="element1">Element 1:</label><br> <input type="text" class="textbox" name="element1" placeholder="element1"><br> <label for="element2">Element 2:</label><br> <input type="text" class="textbox" name="element2" placeholder="element2"><br> <br> <input type="radio" name="operator" value="add"> Add <input type="radio" name="operator" value="subtract"> Subtract <input type="radio" name="operator" value="multiply"> Multiply <input type="radio" name="operator" value="divide"> Divide<br> <br> <input type="submit" id="submitButton" name="submit" value="Calculate"> </form>
Here goes code for style.css which adds styling to the calculator-
margin: 0 auto;
Code in brief
We created a form in our HTML code, consisting of two text fields to provide the input numbers, a button group of radio-buttons which allows us to choose the operator, and a submit button which submits the data.
Notice that the action is taken on the “/” route, and the method is “post”. This implies that a post request will be made to the home route once the user submits the form.
Add the following code in app.js to require the packages that we have already installed i.e., express and body-parser-
const express = require("express");
const bodyParser = require(“body-parser”);
const app = express();
Express by default serves only the HTML code, so we must explicitly tell it to serve the static files in our folder ‘public’, hence the last line.
Now, configure our app to connect to a server through a port, in this case, port 3000.
console.log(“Server started on post 3000”);
Now, run “node app.js” command in prompt. If we get the message we tried to log in code, then congrats, the server has been connected successfully. Press ctrl+c to stop the connection.
Here, we send the requests from the browser to the server, and the servers’ response is displayed on the browser. If we type URL https://localhost:3000/ on the browser, it sends the first request i.e., a get request to route “/”, this is where we need to display our index.html. Add the following code to send a response to the browser in case of a get request. “__dirname” gives the directory you currently are in.
Observe that in our HTML code, the form takes action on the “/” route with the method post, it means once the form is submitted, a post request is sent to the home route “/” from the browser. So add the following code to send a response from the server when a post request is initiated-
var e1 = Number(request.body.element1);
var e2 = Number(request.body.element2);
case "add": result = e1+e2; break; case "subtract": result = e1-e2; break; case "multiply": result = e1*e2; break; case "divide": result = e1/e2; break; default: result = "error";
The result is: “+result+”
body-parser gives us access to request elements. Ex: req.body.element1, here element1 is the value of the name attribute of the first input, similarly for others.
response.send is used to send the response to the browser, we need to provide the required HTML inside quotes.
Hola, now go to the browser and give the address https://localhost:3000/ and see our website up and running. Don’t forget to connect to the server by “node app.js” in prompt before moving to the browser.
In websites like blogs, if we observe, all the data of a session gets lost once we restart the server and start another session on the browser.
How to tackle this problem?
Actually, this happens because once we restart the server, the data structures like arrays get set to their default value, completely erasing our data generated from the memory. So we need a persistent way to store our data, and we achieve that, indeed, by using databases.
A database is an organized collection of structured information, or data, typically stored electronically in a computer system. A database is usually controlled by a database management system (DBMS).
There are two types of databases, SQL and NoSQL. In SQL, the data is stored in the form of table records, whereas in the latter, it is stored as JSON objects.
The SQL database is known for its ability to establish relations between data, whereas NoSQL databases for their flexibility. You need to choose one based on the application’s requirements.
Application Programming Interfaces
An API is a software intermediary that allows two applications to talk to each other. In other words, an API is a messenger that delivers your request to the provider that you’re requesting it from and then delivers the response back to you.
Let us say, you are building a website that requires the current weather condition to display. How will you get the data everytime you run your application on the browser?
Well, you can request the data from a standard weather website with the help of its API and interpret the required lines, again from the documentation, in your code.
An API defines functionalities that are independent of their respective implementations, which allows those implementations and definitions to vary without compromising each other. Therefore, a good API makes it easier to develop a program by providing the building blocks.
In the application we built, we need to explicitly turn on the server to get the app running and it only runs on our system i.e., localhost. Instead, we can deploy our application to real-world servers which are always up and running so we get a link that we can share and our application runs on any computer/ system. You can choose the server you want to deploy your application to and follow its documentation to finish the process.