Introduction to the Fancy JavaScript Request

An introduction to making requests with JavaScript using different methods, includes references about HTTP methods, requests, headers, and more.

The JavaScript request functions allow clients to exchange data from all server-side and client-side resources. The request works by transferring data (sends and receives) from the client-side to the server-side by making what’s known as HTTP requests. These HyperText Transfer Protocol (HTTP) requests work with the fetch and other functions to communicate with the server.

Introduction to the Fancy JavaScript Request
Introduction to the Fancy JavaScript Request

Interestingly, the internet consists of different servers. These servers are a network of interconnected computers, where the browser fetches most website files from. Surfing the internet and navigating through the various pages is the same as users requesting the web browser to fetch the information from the servers. In this short but detailed reference, however, we shall take a closer look at everything you need to instruct web pages to fetch files using different JavaScript request functions.

  1. Fetching With the Fetch Function
  2. Using the XMLHttpRequest Function

HTTP Request

Clients make HTTP Requests to specific hosts. These named hosts are located on servers, and the goal is to communicate with those hosts to access the resources stored on the servers. It is important to note that for a user to make the request, they have to use the components of a request. These components include a request line, URL (also referred to as Uniform Resource Locator), a method, a series of HTTP header fields, and a message body.

An HTTP request may also contain an entity. The entity consists of entity-headers and an optional entity-body, which an entity-body is only present if there is a message-body. The entity-body comes from the format and encoding of the message-body and is represented in the entity-headers. On the other hand, entity-headers describe the message-body or the resource if no body is present. Depending on the request, some of the entity-headers below are required or are optional.

Here are example of enity-headers fields:

  • Allow
  • Content-Encoding
  • Content-Language
  • Content-Length
  • Content-Location
  • Content-MD5
  • Content-Range
  • Content-Type
  • Expires
  • Last-Modified

What is a Request-Line?

The request line, just as we’ve highlighted below, starts with a method token and is followed by the Request-URL, coupled with the protocol version. It ends with CRLF. All of these elements are separated by space SP characters.

What does a request line look like?

Request-Line = Method SP Request-URI SP HTTP-Version CRLF

The request line looks something like this with real data below. This example fetches the contents of example.com’s home page.

GET https://example.com HTTP/1.1

Request-URI

The (the Request-URI) is a Uniform Resource Identifier, and it identifies the current resource on which to apply the selected request. Highlighted below are the most commonly used forms developers use to specify a URI.

  • “*”
  • Abs_path
  • absoluteURI
  • authority

The Request-URI structure is illustrated below:

Request-URI = "*" | absoluteURI | abs_path | authority

Using real data again we can construct a simple Request-URI below which contains a scheme name, authority, path, query, and fragment:

https://example.com:80/search?s=ufo#real

The HTTP Methods

The method token indicates which of the HTTP methods will be performed on the resource highlighted by the Request-URI. But remember, they are case-sensitive. Thus, we believe it would be best always to mention methods in uppercase. In the table below, we’ve highlighted the supported methods in HTTP/1.1.

METHODDESCRIPTION
HEADThe Head method transfers the status line and the header section, and it does nothing else aside from these two purposes stated earlier.
GETSame as Head, though it is used to retrieve information from the specific server. It uses a given URL (Uniform Resource Locator). Requests with this method (Get) should and will only retrieve data; it has no other effect on the data sourced.
PUTThe PUT method replaces all the representations of the fetched resource, coupled with the uploaded content.
POSTThis request is used to transfer data to the server. A perfect example of this is file upload or customer order information. These are done using HTML forms.
TRACEThe trace method helps to perform a message loop back test coupled with the path to the target data resource.
CONNECTConnect establishes a tunnel to the specific server, which a given URI will identify.
DELETEDelete removes the representations of the target resource, which URI gives.
OPTIONSThe Option is a method that describes the current communication options for the target resource.

Building a Simple Page

First, before we attempt to create a JavaScript request, we will need to create a simple web page to load the results of the request we will be making. The examples below will walk you through creating a simple web page that retrieves the user’s IP address. We will be demonstrating two JavaScript functions that can achieve a request.

HTML Code

<div class="box">
  <title>Display IP Address</title>
  <h2 id="center">Appcode JavaScript Tutorial</h2>
  <h3 id="center" class="down"> Getting the JavaScript request with the fetch method</h3>
  <p class="top">( Here's the IP Address of your machine: )</p>
  <h1 id=ipAddress></h1>
</div>

CSS Code

body, html {
  background-color:#add8e6;
  font-family: Arial;
  margin: 0;
  height: 100%;
}

h1 {
  font-family: sans-serif;
  text-align: center;
  padding-top: 40px;
  font-size: 40px;
}

p {
  font-family: sans-serif;
  color: #000000;
  text-align: center;
}

.center {
  align: center;
}

#center {
  text-align: center;
}

.down {
  margin-bottom: 50px;
}

.top {
  margin-bottom: -30px;
}

Fetching With the Fetch Function

The syntax of the JavaScript request function will look something like this:

var request = new Request(sample_url: String, [init: Object]);

JavaScript Code

// You can use the var request variable above or provide a url in the fetch function 
// fetch(request) or fetch("url")
fetch("https://ipinfo.io/json")
  .then(function (response) {
    return response.json();
  })
  .then(function (ipJson) {
    document.querySelector("#ipAddress").innerHTML = ipJson.ip;
  })
  .catch(function (error) {
    console.log("Error: " + error);
  });

Here’s what the result would look like using the fetch() function:

JavaScript Request Using The Fetch Function
JavaScript Request Using The Fetch Function

You can play around with the code which is found on codepen.io

Using the XMLHttpRequest Function

Alternatively, you may use the XMLHttpRequest function instead of the fetch function. The XMLHttpRequest function will achieve the same results.

JavaScript Code

let IPxhr = new XMLHttpRequest();
IPxhr.open("GET", "https://ipinfo.io/json", true);
IPxhr.send();
IPxhr.onreadystatechange = processRequest;
function processRequest(e) {
  if (IPxhr.readyState == 4 && IPxhr.status == 200) {
    let response = JSON.parse(IPxhr.responseText);
    document.querySelector("#ipAddress").innerHTML = response.ip;
  }
}

Conclusion

Hopefully, with what you’ve learned so far, handling different JavaScript Requests types won’t be a hassle for you. First, we’ve described what some HTTP methods are. Secondly, we highlighted the commonly used JavaScript request types, including XMLHTTPRequest and the fetch functions. Finally, we’ve provided you with some code examples to play around with and use.

Remember, incorporating HTTP Request methods and returning data remains one of the simplest tasks to do, especially when you are still new to the JavaScript language. But with time, not only will you understand the functionality, but you’ll also know the right one to use in any given scenario.

Recommended Articles