JavaScript Journal: Fetching Data using HTTP Requests

JavaScript Journal: Fetching Data using HTTP Requests

A Daily Quest for Mastery

Introduction

In the world of web development, JavaScript plays a crucial role in creating dynamic and interactive websites. One fundamental aspect of web development is the ability to communicate with servers and retrieve or send data. This is where HTTP requests come into play.

In this article, we will delve into the concept of HTTP requests in JavaScript, exploring the different types of requests and how they are used. We will also learn the techniques available in JavaScript to make these requests and the HTTP status codes.

Expectation

By the end of this article, you will have a solid knowledge and understanding of how HTTP requests work in JavaScruot and be equipped with the knowledge to incorporate these requests into your web development projects.

What is HTTP

Hypertext Transfer Protocol (HTTP) is the protocol used for communication between clients (such as web browsers) and servers. To simply put it, HTTP is the protocol for sending and receiving data on the web. It is a client/server protocol, which means requests are initiated by the client (you, using the browser), and the server will respond with a request. The response could be HTML, CSS, JavaScript files, images, and other resources, as well as data formatted in JSON or XML.

How it Works

Making HTTP Requests in JavaScript

To make HTTP requests in JavaScript, there are different approaches. But, we can use the traditional built-in XMLHttpRequest object or the modern fetch() function.

XMLHttpRequest

The XMLHttpRequest (XHR) object was the original way of making requests. It has been available in JavaScript for a long time and is still widely used. It provides a way to make asynchronous HTTP requests.

Here's an example of how to use XMLHttpRequest to make a request.

// Creating a new XMLHttpRequest object
let xhr = new XMLHttpRequest();

// Opening a GET request to 'https://api.example.com/data' asynchronously
xhr.open('GET', 'https://api.example.com/data', true);

// Setting up an event handler for when the request loads
xhr.onload = function() {
   // Check if the status code is 200 (successful)
   if (chr.status === 200) {
     // Parseing the response text as JSON
     let data = JSON.parse(xhr.responseText);
     // Processing the retrieved data
     console.log(data)
  }
};

// Setting up an event handler for handling request errors
xhr.onerror = function() {
   // Handle any errors that occur during the request
   console.error('Request failed.')
};

// Sending the request
xhr.send();

In the code snippet above, we create a new XMLHttpRequest object and use the open() method to specify the type of request (GET), the URL we want to request, and whether the request should be asynchronous (true in this case). We then set up event handlers such as onload to handle the response when it arrives. Lastly, we call the send() method to initiate the request.

fetch() Function

The fetch() function is a newer and more modern approach for making HTTP requests. It provides a simpler and more intuitive API, taking advantage of Promises for handling asynchronous operations.

Here's an example of how to use fetch() to make a request

// Making a GET request to API 'https://api.example.co/data' using fetch() function
fetch('https://api.example.com/data')

   // Handling the response using a Promise-based approach
   .then(response => {

      // Checking if the response's 'ok' property is true (indicating a successful response)
      if (response.ok) {
         return response.json();
      } else {
         // Throwing an error to be caught in the next 'catch()' block
         throw new Error('Request failed.');
      }
   })

   // Handling the retrieved data
   .then(data => {
      // Processing the retrieved data
      console.log(data);
   })

  // Handling any errors that occur during the request
   .catch(error => {
      console.log(errors);
   })

In the code snippet above, we use the fetch() function providing the URL we want to request as the argument. It returns a Promise, allowing us to chain .then() to handle the response. We check first if the response is successful (status code 200). If successful, we parse the response as JSON using the .json() method if the response is not successful, we throw an error. Finally, we handle any errors that occur during the request using .catch()

The XMLHttpRequest and fetch() function offer similar functionality, but the fetch() is generally considered more modern and provides a simpler and more flexible API. However, XMLHttpRequest may still be useful in certain instances, for example; for compatibility with older browsers.

HTTP Methods

The following list contains some of the most commonly used HTTP methods. Each method has its specific purpose and context, allowing clients (you) to interact with servers in a standard way. It's important to use the appropriate method based on the intended action you want to perform on the server's resources.

  1. GET: This method is used to only fetch/retrieve data from the server. For example, when you visit a webpage or load an image, your browser sends a GET request to fetch that content.

  2. POST: The post method is used to send or submit data to the server for processing. When you submit a form on a website, the form data is typically sent to the server using a POST request.

  3. PUT: The PUT method is used to update existing data on the server. It replaces the old data with the new data provided in the request. For example, you can use a PUT request to update a user's profile information.

  4. DELETE: The DELETE request is used to delete data r resources on the server. It requests the server to remove specified data. For instance, you can use a DELETE request to delete a post or remove a user account.

HTTP Status Code

HTTP(Hypertext Transfer Protocol) status codes are three-digit numbers returned by servers to indicate the outcome of a client's request. They provide information about the success or failure of a request and help in diagnosing issues in web communication. Status codes are grouped into different categories, making it easier to identify request responses. Here's an overview of the different categories of HTTP status codes:

  1. Informational Responses (100 Range)

    • 100 Continue: The server has received the initial part of the request and Is waiting for the client to send the remaining parts.

    • 101 Switching Protocols: The server acknowledges the client's request to switch protocols (e.g. from HTTP to WebSocket).

  2. Successful Responses (200 Range):

    • 200 OK: The request has succeeded, and the server is sending the requested data as a response.

    • 201 Created: The request has been fulfilled, and a new resource has been created as a result.

    • 204 No Content: The server has fulfilled the request, but there is no content to send back.

  3. Redirection Messages (300 Range):

    • 301 Moved Permanently: The requested resource has been permanently moved to a new URL.

    • 302 Found: The requested resource has been temporarily moved to a different URL.

    • 304 Not Modified: The client's cached version of the requested resource is still valid, and the server responds with no content.

  4. Client Error Responses (400 Range):

    • 400 Bad Request: The server cannot process the client's request due to malformed syntax or invalid parameters.

    • 403 Forbidden: The client does not have permission to access the requested resource.

    • 404 Not Found: The requested resource could not be found on the server.

  5. Server Error Responses (500):

    • 500 Internal Server Error: An unexpected condition occurred on the server, preventing it from fulfilling the request.

    • 502 Bad Gateway: The server acting as a gateway or proxy received an invalid response from an upstream server.

    • 503 Service Unavailable: The server is temporarily unable to handle the request due to maintenance or high load.

Conclusion

In this article, we covered the fundamental concepts and techniques for interacting with servers and retrieving data. We also discussed the two common methods for making HTTP requests: XMLHttpRequest and fetch() function.

Furthermore, we also looked at the commonly used HTTP methods, such as GET, POST, PUT, and DELETE. Each method or request serves a specific purpose, enabling clients to fetch, create, update, or delete data on a server.

Lastly, we looked at how to identify responses using HTTP status codes to ensure proper handling and user experience in web development.

I hope this article provides you with an understanding of making HTTP requests in JavaScript using XMLHttpRequest and fetch().

Credits

Cover Image by Juan Cruz Martinez