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.
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.