Let's Begin

The very important topics to know.

HTTP or Hypertext Transfer Protocol

I see this everywhere, what is it?

It is a set of rules and protocols that are used for communication on the World Wide Web . It is also the foundation of data communication on the internet, and it is the underlying protocol that enables the exchange of information between web browsers and web servers.

In general, the HTTP protocol defines how messages are formatted and transmitted, and what actions web servers and clients should take in response to various commands. When a user enters a web address into their web browser, the browser sends an HTTP request message to the web server that hosts the website, and the server responds with an HTTP response message that contains the requested webpage or other information.

It is a stateless, client-server protocol, which means that each request message is independent of any previous request, and that the server does not store any information about the client between requests. HTTP is also a textual protocol, which means that the messages are formatted as text, and can be read and written by humans as well as machines.

🧃 JUICY TIP:

HTTPS stands for HTTP Secure and is a secure version of HTTP. It uses a secure SSL/TLS (Secure Sockets Layer/Transport Layer Security) connection to encrypt data transmitted between the web server and the client. This makes it more difficult for hackers to intercept and steal sensitive information, such as passwords or credit card numbers, during transmission.

HTTP methods

HTTP methods, also known as HTTP verbs, are the commands that a client uses to tell a server what it wants to do with a particular resource. The most common HTTP methods are GET, POST, PUT, and DELETE , and they correspond to the four most common CRUD (create, read, update, delete) operations that are used in database management systems.

Here is a brief overview of each of the HTTP methods and how they are typically used:

  • GET - Used to retrieve a resource from the server like data from an API or web service. It is the most commonly used HTTP method.
  • POST - Used to submit data to the server, usually for the purpose of creating a new resource such as when a user fills out a form on a website.
  • PUT - Used to update an existing resource on the server, like when a client wants to replace an existing resource with a new version.
  • DELETE - Used to delete a resource from the server.

These HTTP methods are used to specify the desired action that the client wants the server to take on the specified resource. The server will then respond with an HTTP response message that indicates whether the request was successful or not, and it will include the requested data or an error message in the response body.

HTTP headers

HTTP headers are the name-value pairs that are included in the header section of an HTTP request or response message. They are used to provide additional information about the request or response, such as the content type and length of the message body, the allowed methods for the request, and the status code of the response.

They are a fundamental part of the HTTP protocol, and are used to convey a wide range of information about the request or response. For example, the Content-Type header is used to specify the media type of the request or response body, while the Content-Length header is used to specify the length of the body in bytes.

Ok, show me.

Here is an example of an HTTP request message that a web browser might send to a web server to request a webpage:

GET /index.html HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Upgrade-Insecure-Requests: 1

In this example, the request is a GET request that is asking the server to send the index.html file from the root directory of the www.example.com website. The request also includes a number of HTTP headers that provide additional information about the request, such as the type of browser that is making the request, the preferred languages and content types, and the connection type.

When the server receives this request, it will respond with an HTTP response message that contains the requested webpage or an error message, if the requested resource is not found. The response message will also include its own set of HTTP headers.

HTTP Status Codes

HTTP status codes are standardized codes that are used to communicate the status of a request made to a server. They are divided into five categories:

  1. Informational (100-199): These codes are used to indicate a provisional response to a request.
  2. Success (200-299): These codes are used to indicate that a request has been successfully completed, some of them are:
    • 200 OK: This code indicates that the request was successful and that the requested information is being returned.
    • 201 Created: The request succeeded, and a new resource was created as a result. This is typically the response sent after POST requests, or some PUT requests.
    • 204 No Content: This code indicates that the request was successful, but there is no information to be returned.
  3. Redirection (300-399): These codes are used to indicate that the client needs to take additional action in order to complete the request, for example:
    • 301 Moved Permanently: This code indicates that the requested resource has been moved permanently to a new location.
    • 302 Found: This code indicates that the requested resource has been temporarily moved to a new location.
  4. Client Error (400-499): These codes are used to indicate that there was an error on the client side and the request cannot be completed, like:
    • 400 Bad Request: This code indicates that the request was invalid or cannot be completed.
    • 401 Unauthorized: This code indicates that the client must authenticate itself to get the requested response.
    • 403 Forbidden: This code indicates that the client does not have permission to access the requested resource.
    • 404 Not Found: The server cannot find the requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 Forbidden to hide the existence of a resource from an unauthorized client. This response code is probably the most well known due to its frequent occurrence on the web.
  5. Server Error (500-599): These codes are used to indicate that there was an error on the server side and the request cannot be completed. Some common codes in this category include:
    • 500 Internal Server Error: This code indicates that an unexpected condition was encountered by the server and no more specific message is suitable.
    • 502 Bad Gateway: This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response.
    • 503 Service Unavailable: This code indicates that the server is currently unable to handle the request due to a temporary overload or maintenance.
    • 504 Gateweay Timeout: This error response is given when the server is acting as a gateway and cannot get a response in time.

There are many other HTTP status codes in addition to the ones listed above, and they are used to provide more detailed information about the status of a request.

APIs

Everyone has one, but what does it mean?

API is short for Application Programming Interface . It is a set of rules and protocols for building and integrating application software. It specifies how software components should interact with each other and defines the interfaces between them.

They are used in many different contexts, for example, a web-based email service like Gmail provides an API that allows developers to build applications that can send and receive email messages. Similarly, a weather forecasting service like OpenWeatherMap provides an API that allows developers to build applications that can access current and forecasted weather data.

APIs are typically accessed over a network using the Hypertext Transfer Protocol (HTTP) , and they can return data in a variety of formats, such as XML, JSON, or CSV. They can be either public or private, and they can be used to enable a wide range of applications and services.

RESTful architecture

I love to rest aswell.

No... RESTful (Representational State Transfer) is an architectural style based on the principles of REST , used for building distributed systems.

These principles are:

  • Client-server architecture - The client and server are separate and independent components, which means that they can be developed and deployed independently of each other. This also means that the client and server can be implemented using different technologies and programming languages.
  • Statelessness - The server does not store any information about the client between requests. The server does not have to store any session information or manage state.
  • Cacheability - The responses from the server can be stored by the client or a caching proxy in order to improve performance. This means that the client can reuse the same response data without having to make a new request to the server.
  • Uniform interface - All resources are accessed using the same set of methods and the same URLs. This makes RESTful architectures easy to use and understand, because the client only needs to know the base URL of the web service in order to access all of the resources.
  • Layered system - They can be composed of multiple layers of components that are each responsible for a specific aspect of the service. This makes RESTful architectures flexible and extensible, because new layers can be added or existing layers can be replaced without impacting the other layers.

By following these principles, RESTful architectures enable the development of web services and APIs that are scalable, flexible and easy to use.

Callback Functions

What are they?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. They can either be synchronous or asynchronous.

Here is a quick example:

function greeting(name) {
  alert('Hello ' + name);
}

function processUserInput(callback) {
  let name = prompt('Please enter your name.');
  callback(name);
}

processUserInput(greeting);

What is Synchronous?

Synchronous refers to real-time communication where each party receives (and if necessary, processes and replies to) messages instantly (or as near to instantly as possible).

A human example is the telephone, during a telephone call you tend to respond to another person immediately. Many programming commands are also synchronous, for example when you type in a calculation, the environment will return the result to you instantly, unless you program it not to.

What about Asynchronous?

The term asynchronous refers to two or more objects or events not existing or happening at the same time (or multiple related things happening without waiting for the previous one to complete). In computing, the word asynchronous is used in two major contexts.

1. Networking and communication

Asynchronous communication is a method of exchanging messages between two or more parties in which each party receives and processes messages whenever it's convenient or possible to do so, rather than doing so immediately upon receipt. Additionally, messages may be sent without waiting for acknowledgement, with the understanding that if a problem occurs, the recipient will request corrections or otherwise handle the situation.

For humans, e-mail is an asynchronous communication method; the sender sends an email and the recipient will read and reply to the message when it's convenient to do so, rather than doing so at once. And both sides can continue to send and receive messages whenever they wish, instead of having to schedule them around each other.

When software communicates asynchronously, a program may make a request for information from another piece of software (such as a server), and continue to do other things while waiting for a reply. For example, the AJAX (Asynchronous JavaScript and XML) programming technique, even though JSON is usually used rather than XML in modern applications—is a mechanism that requests relatively small amounts of data from the server using HTTP, with the result being returned when available rather than immediately.

2. Software design

Asynchronous software design expands upon the concept by building code that allows a program to ask that a task be performed alongside the original task (or tasks), without stopping to wait for the task to complete. When the secondary task is completed, the original task is notified using an agreed-upon mechanism so that it knows the work is done, and that the result, if any, is available.

The Real Stuff

Also very important to know 🤔 ?

Asynchronous Javascript Methods

Promises

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It contains both the producing code and calls to the consuming code:

let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)

  myResolve(); // when successful
  myReject();  // when error
});

// "Consuming Code" (Must wait for a fulfilled Promise)
myPromise.then(
  function(value) { /* code if successful */ },
  function(error) { /* code if some error */ }
);

When the producing code obtains the res ult, it should call one of the two callbacks:

  • Success -> myResolve(result value)
  • Error -> myReject(error object)

A Fancier Description

A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

Promise Object Properties

The Promise object supports two properties, state and result.

The state and result can be:

  • Pending: initial state, neither fullfilled nor rejected. Result is Undefined.
  • Fulfilled: meaning that the operation was completed successfully. Result is a Value.
  • Rejected: meaning that the operation failed. Result is an Error Object.

🧃 JUICY TIP:

You cannot access the Promise properties state and result. You must use a Promise method to handle promises.

Async / Await

The async function declaration declares an async function where the await keyword is permitted within the function body. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains like the example above.

async function getData() {
  const response = await fetch('https://my-api.com/data');
  const data = await response.json();
  return data;
}

API Fetching

AJAX

What is it?

AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files. AJAX's most appealing characteristic is its asynchronous nature, which as we learnt, means it can communicate with the server, exchange data, and update the page without having to refresh the page.

Here's an example of how you can use XMLHttpRequest to make an HTTP GET request to retrieve data from a server:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.example.com/api/data');
xhr.onload = function() {
  if (xhr.status === 200) {
    // Request successful, do something with the data
    const data = JSON.parse(xhr.responseText);
    console.log(data);
  } else {
    // Request failed, handle the error
    console.error(xhr.statusText);
  }
};
xhr.onerror = function() {
  // Request failed, handle the error
  console.error(xhr.statusText);
};
xhr.send();

FetchAPI

So, what it means?

The fetch() API is a modern way to make network requests in JavaScript. It provides a more powerful and flexible way to send HTTP requests than the older XMLHttpRequest object.

It is available in most modern browsers, and it allows you to make HTTP requests to a server and receive a response. It returns a promise, which means you can use the then() method to specify what should happen when the request is successful, and the catch() method to handle any errors that occur.

fetch('https://www.example.com/api/data')
  .then(response => response.json())
  .then(data => {
    // Do something with the data
    console.log(data);
  })
  .catch(error => {
    // Handle the error
    console.error(error);
  });

Overall, the fetch() API provides a more modern and convenient way to make HTTP requests.

Axios

Is this another mythological god?

Hehe, funny. Axios is a popular promise-based HTTP client that enables JavaScript developers to easily send HTTP requests to back-end APIs and also handle its response.

To use Axios in React, you can use the axios package as a third-party library. Here is an example of how to use Axios to make an HTTP GET request to fetch data:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

function MyComponent() {
  const [data, setData] = useState(null);

  useEffect(() => {
    axios
      .get('https://my-api.com/endpoint')
      .then(response => setData(response.data))
      .catch(error => console.error(error));
  }, []);

  return (
    <div>
      {data ? (
        <div>
          <h1>Data received from the API:</h1>
          <pre>{JSON.stringify(data, null, 2)}</pre>
        </div>
      ) : (
        <p>Loading data...</p>
      )}
    </div>
  );
}

A little Extra

XML

eXtensible Markup Language (XML) is a generic markup language specified by the W3C (World Wide Web Consortium). The information technology industry uses many languages based on XML as data-description languages.

XML tags resemble HTML tags, but XML is much more flexible because it lets users define their own tags. In this way XML acts like a meta-language, that is, it can be used to define other languages, such as RSS. Moreover, HTML is a presentation language, whereas XML is a data-description language. This means that XML has far broader applications than just the Web. For example, Web services can use XML to exchange requests and responses.

JSON

JavaScript Object Notation JSON is a data-interchange format. Although not a strict subset, JSON closely resembles a subset of JavaScript syntax. Though many programming languages support JSON, it is especially useful for JavaScript-based apps, including websites and browser extensions.

JSON can represent numbers, booleans, strings, null, arrays, and objects made up of these values (or of other arrays and objects). JSON does not natively represent more complex data types like functions, regular expressions, dates, and so on. (Date objects by default serialize to a string containing the date in ISO format, so the information isn't completely lost.) If you need it to represent additional data types, transform values as they are serialized or before they are deserialized.

SSR and SSG

Server-Side Rendering SSR refers to the practice of rendering a client-side JavaScript application on the server, before sending the fully rendered page to the client. This can improve the performance of the application, as the client does not need to wait for the JavaScript to load and execute before being able to see the content of the page.

Static Site Generation SSG refers to the practice of generating a set of static HTML files from a collection of content and templates. This can be done either at build time or runtime.

What are the differences?

SSR involves rendering the content on the server at the time of the request, while SSG involves generating the content ahead of time and serving pre-rendered pages. This means that SSG is more suitable for sites that do not require frequent updates or have content that does not change often, while SSR is better suited for sites that have more dynamic content or need to be updated frequently.