JavaScript Programming Languages

JavaScript HTTP Requests 101: Everything You Need to Know

Reading Time: 3 mins

HTTP requests are an essential part of web development, as they allow you to send and receive data from servers and APIs. In this article, we’ll take a look at how to make HTTP requests in JavaScript using the XMLHttpRequest object and the newer fetch() API.

two black flat screen computer monitors
Photo by Miguel Á. Padriñán on Pexels.com

Using the XMLHttpRequest Object

The XMLHttpRequest object is a built-in JavaScript object that allows you to make HTTP requests from within your script. It was the original way to make asynchronous requests in JavaScript and is still widely used today.

To use the XMLHttpRequest object, you’ll need to create a new instance of it and then use its various methods and properties to configure and send the request. Here’s an example of how to make a simple GET request to a server using the XMLHttpRequest object:

const xhr = new XMLHttpRequest();
xhr.open("GET", "http://example.com/api/endpoint");
xhr.send();

The open() method is used to specify the type of request (in this case, a GET request) and the URL of the resource you want to retrieve. The send() method is used to actually send the request.

You can also use the XMLHttpRequest object to make POST requests, by changing the first argument of the open() method to “POST” and specifying any data you want to send in the request body as the second argument of the send() method. For example:

const xhr = new XMLHttpRequest();
xhr.open("POST", "http://example.com/api/endpoint");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify({ name: "John Smith" }));

In this case, we’re using the setRequestHeader() method to set the Content-Type header to application/json, to indicate that the request body is in JSON format. We’re also using the JSON.stringify() function to convert the JavaScript object into a JSON string.

To handle the response from the server, you can use the onload event of the XMLHttpRequest object. This event is fired when the request is completed and the response is available. Here’s an example of how to use the onload event to output the response to the console:

const xhr = new XMLHttpRequest();
xhr.open("GET", "http://example.com/api/endpoint");
xhr.onload = function () {
  console.log(this.responseText);
};
xhr.send();

In this case, we’re using the responseText property of the XMLHttpRequest object to access the response from the server as a string.

Using the fetch() API

The fetch() API is a newer way to make HTTP requests in JavaScript and uses a Promises-based syntax. It’s similar to the XMLHttpRequest object in many ways, but has a cleaner syntax and supports other features like streaming responses and cancellation.

Here’s an example of how to make a GET request using the fetch() API:

fetch("http://example.com/api/endpoint")
  .then((response) => response.text())
  .then((data) => console.log(data));

In this case, we’re using the fetch() function to make a GET request to the specified URL. The fetch() function returns a Promise that resolves to an Response object, which contains the response from the server.

We can chain a then() method to the Promise returned by fetch(), which allows us to process the response. In this example, we’re using the text() method of the Response object to convert the response to a string and then using another then() method to log the response to the console.

To make a POST request using the fetch() API, you can pass an options object as the second argument to the fetch() function. This object can include various properties to configure the request, such as the method property to specify the request type (in this case, “POST”) and the body property to specify the request body. Here’s an example of how to make a POST request using the fetch() API:

fetch("http://example.com/api/endpoint", {
  method: "POST",
  body: JSON.stringify({ name: "John Smith" }),
  headers: {
    "Content-Type": "application/json",
  },
})
  .then((response) => response.text())
  .then((data) => console.log(data));

In this case, we’re using the headers property to set the Content-Type header to application/json, to indicate that the request body is in JSON format. We’re also using the JSON.stringify() function to convert the JavaScript object into a JSON string.

Conclusion

In this article, we’ve seen how to make HTTP requests in JavaScript using the XMLHttpRequest object and the newer fetch() API. Both of these methods allow you to send and receive data from servers and APIs and are an essential part of web development.

Related Posts

white and black jigsaw puzzle

Implementing Binary Search Algorithm for Efficient Searching of Sorted Arrays

Reading Time: 2 minsThis blog post explains how to implement the binary search algorithm in Java to search for an integer in a sorted array. Binary search is a very efficient search algorithm that works on sorted data and operates by repeatedly dividing the search interval in half. By using binary search, we can search a large array in logarithmic time, which is much faster than linear search. We’ll walk through the implementation of binary search in Java, including the use of iterative algorithms and divide and conquer techniques, and how to apply it to search for an integer in a sorted array.

house underneath cumulus clouds

How to Build a Weather Application using Node.js and Weather APIs

Reading Time: 3 minsIn this tutorial, you learned how to build a simple weather application using Node.js and APIs from OpenWeatherMap, DarkSky, or AccuWeather. You also learned how to make HTTP requests using the built-in Node.js http module and how to load environment variables from a .env file using the dotenv package. With these skills, you can build and customize your own weather application or apply them to other APIs and use cases.

man in black long sleeve shirt wearing black headphones sitting on chair

Why JavaScript is Crucial for Your Website’s Success: 7 Advantages You Can’t Ignore

Reading Time: 4 minsJavaScript is a popular programming language that is essential for modern web development. It enables developers to create interactive and dynamic web pages, improve the user experience, and boost SEO. In this article, we’ll explore the top benefits of using JavaScript for web development, including website functionality, performance, cross-platform compatibility, and more. Whether you’re a beginner or an experienced developer, understanding the advantages of JavaScript can help you create more powerful and effective websites and applications.

person in gray shirt holding a small paper with texts

Master Your Next Java Interview with These 50 Expert-Approved Questions and Answers

Reading Time: 12 minsJava is a popular programming language that is widely used in the development of enterprise applications, web applications, mobile applications, and more. As a result, Java developers are in high demand and a strong understanding of the language is essential for success in the field. In this article, we’ve compiled a list of the top 50 Java interview questions and answers to help you prepare for your next interview and ace it with confidence.

people walking on sidewalk during daytime

From Netscape to Node: The Evolution of JavaScript as a Leading Web Development Language

Reading Time: 4 minsJavaScript is a programming language that was first introduced in 1995. It is a high-level, dynamic, and interpreted language that is widely used in web development to create interactive and engaging web applications. JavaScript is supported by all modern web browsers, making it an essential tool for front-end web development. In this article, we will explore the history and development of JavaScript, as well as its key features and capabilities. We will also discuss the current state of JavaScript and its future prospects.

MacBook Pro

The 5 most useful Javascript tips for web developers

Reading Time: 7 minsIf you’re a web developer, chances are you’re always on the lookout for ways to improve your workflow and get things done faster. Javascript is a versatile language…

Leave a Reply