Understanding HTTP requests is fundamental for any web development project, as they enable communication between clients and servers. In this blog post, we will delve into making HTTP requests using two popular JavaScript methods: Fetch API and XMLHttpRequest (XHR). By the end, you’ll have a comprehensive understanding of how to use these techniques in your own projects.
Table of Contents
Introduction to HTTP Requests in Javascript
HTTP requests are the foundation of web interactions. They allow clients (such as web browsers) to communicate with servers, fetching or sending data as required. The four primary HTTP methods to interact with servers are:
- GET: Retrieve data from a server.
- POST: Send new data to a server.
- PUT: Update existing data on a server.
- DELETE: Remove data from a server.
Detailed Explanation of HTTP Methods
GET: Retrieve Data from a Server
The GET method is used to request data from a specified resource. It is one of the most common HTTP methods and is typically used to retrieve data from a server without making any changes to the resource. When a GET request is made, any parameters are usually sent in the URL, and the server responds with the requested data.
POST: Send New Data to a Server
The POST method is used to send data to a server to create a new resource. Unlike GET requests, POST requests send data in the body of the request rather than in the URL. This method is commonly used for submitting forms, uploading files, or sending user-generated content to a server. The server processes the data and typically returns a response indicating the success or failure of the operation.
PUT: Update Existing Data on a Server
The PUT method is used to update an existing resource on a server. Similar to POST, PUT requests send data in the body of the request. However, the key difference is that PUT is idempotent, meaning that making multiple identical PUT requests will produce the same result as making a single request. This method is often used for updating user information or modifying existing data on a server.
DELETE: Remove Data from a Server
The DELETE method is used to remove a specified resource from a server. When a DELETE request is made, the server deletes the resource. This method is typically used for deleting records or data entries from a database. Like PUT, DELETE is idempotent, meaning that making multiple identical DELETE requests will have the same effect as making a single request.
For a more detailed understanding of HTTP methods, you can refer to the MDN Web Docs on HTTP Methods.
Making HTTP Requests with Fetch API
The Fetch API is a modern interface for making HTTP requests. It is promise-based, which simplifies handling asynchronous operations and makes the code cleaner and more readable.
Fetch API: GET Request
A GET request retrieves data from a server. Lets understand how to perform a GET request using the Fetch API
fetch('https://api.mocki.io/v1/b043df5a')
.then(response => response.json()) // Converts the response to JSON
.then(data => console.log(data)) // Logs the data to the console
.catch(error => console.error('Error fetching data:', error)); // Handles errors
- The fetch function initiates a GET request to the specified URL.
- The
then
method processes the response, converting it to JSON format. - The data is then logged to the console.
- Any errors that are encountered will be handled and logged by the catch method.
Fetch API: POST Request
A POST request sends data to a server. Let’s see the below code and understand.
fetch('https://api.mocki.io/v1/b043df5a', {
method: 'POST', // Specifies the request method as POST
body: JSON.stringify({
name: 'John Doe',
email: 'john.doe@example.com'
}), // Converts the data to a JSON string
headers: {
'Content-Type': 'application/json' // Sets the content type to JSON
}
})
.then(response => response.json()) // Converts the response to JSON
.then(data => console.log(data)) // Logs the data to the console
.catch(error => console.error('Error posting data:', error)); // Handles errors
- The fetch function sends a POST request to the specified URL.
- The
body
property contains the data to be sent, which is converted to a JSON string. - The
headers
property specifies that the content type is JSON. - The response is processed and logged as in the GET request example.
Fetch API: PUT Request
A PUT request updates existing data on the server. Here’s how to do it
fetch('https://api.mocki.io/v1/b043df5a/1', {
method: 'PUT', // Specifies the request method as PUT
body: JSON.stringify({
name: 'Jane Doe',
email: 'jane.doe@example.com'
}), // Converts the data to a JSON string
headers: {
'Content-Type': 'application/json' // Sets the content type to JSON
}
})
.then(response => response.json()) // Converts the response to JSON
.then(data => console.log(data)) // Logs the data to the console
.catch(error => console.error('Error updating data:', error)); // Handles errors
- The
fetch
function sends a PUT request to the specified URL. - The
body
property contains the updated data in JSON format. - The response is processed and logged as in the previous examples.
Fetch API: DELETE Request
A DELETE request removes data from the server. Here’s is the code to understand
fetch('https://api.mocki.io/v1/b043df5a/1', {
method: 'DELETE' // Specifies the request method as DELETE
})
.then(() => console.log('Data deleted successfully')) // Logs success message
.catch(error => console.error('Error deleting data:', error)); // Handles errors
- The fetch function sends a DELETE request to the specified URL.
- A success message is logged if the request is successful.
- Any errors encountered are caught and logged.
Making HTTP Requests with XMLHttpRequest
XMLHttpRequest (XHR) is an older, yet still widely used, method for making HTTP requests. It uses event listeners to handle responses and errors.
XMLHttpRequest: GET Request
Here’s how to perform a GET request using XMLHttpRequest
const getData = (url, callback, errorCallback) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true); // Initializes a GET request
xhr.onload = () => callback(xhr.responseText); // Handles a successful response
xhr.onerror = () => errorCallback(xhr); // Handles errors
xhr.send(); // Sends the request
};
getData('https://api.mocki.io/v1/b043df5a', console.log, console.error);
- First object is created.
- The
open
method initializes a GET request to the specified URL. - The
onload
event handler processes a successful response. - The
onerror
event handler processes any errors. - The
send
method sends the request to the server.
XMLHttpRequest: POST Request
Here’s how to send a POST request
const postData = (url, data, callback, errorCallback) => {
const xhr = new XMLHttpRequest();
xhr.open('POST', url, true); // Initializes a POST request
xhr.setRequestHeader('Content-Type', 'application/json'); // Sets the content type to JSON
xhr.onload = () => callback(xhr.responseText); // Handles a successful response
xhr.onerror = () => errorCallback(xhr); // Handles errors
xhr.send(JSON.stringify(data)); // Converts the data to a JSON string and sends it
};
postData('https://api.mocki.io/v1/b043df5a', {
name: 'John Doe',
email: 'john.doe@example.com'
}, console.log, console.error);
- The
open
method initializes a POST request to the specified URL. - The
setRequestHeader
method sets the content type to JSON. - The
send
method converts the data to a JSON string and sends it to the server.
XMLHttpRequest: PUT Request
Updating data with a PUT request using XMLHttpRequest looks like this
const updateData = (url, data, callback, errorCallback) => {
const xhr = new XMLHttpRequest();
xhr.open('PUT', url, true); // Initializes a PUT request
xhr.setRequestHeader('Content-Type', 'application/json'); // Sets the content type to JSON
xhr.onload = () => callback(xhr.responseText); // Handles a successful response
xhr.onerror = () => errorCallback(xhr); // Handles errors
xhr.send(JSON.stringify(data)); // Converts the data to a JSON string and sends it
};
updateData('https://api.mocki.io/v1/b043df5a/1', {
name: 'Jane Doe',
email: 'jane.doe@example.com'
}, console.log, console.error);
- The
open
method initializes a PUT request to the specified URL. - The
setRequestHeader
method sets the content type to JSON. - The
send
method converts the updated data to a JSON string and sends it to the server.
XMLHttpRequest: DELETE Request
Let’s make a DELETE request using XMLHttpRequest:
const deleteData = (url, callback, errorCallback) => {
const xhr = new XMLHttpRequest();
xhr.open('DELETE', url, true); // Initializes a DELETE request
xhr.onload = () => callback(xhr.responseText); // Handles a successful response
xhr.onerror = () => errorCallback(xhr); // Handles errors
xhr.send(); // Sends the request
};
deleteData('https://api.mocki.io/v1/b043df5a/1', () => console.log('Data deleted successfully'), console.error);
- The
open
method initializes a DELETE request to the specified URL. - The
send
method sends the request to the server. - A success message is logged if the request is successful.
- Any errors encountered are caught and logged.
Conclusion
Whether you choose the modern Fetch API or the reliable XMLHttpRequest, JavaScript offers robust methods for performing HTTP requests. The Fetch API provides a more intuitive and cleaner approach due to its promise-based structure. In contrast, XMLHttpRequest remains a sturdy option, especially for older browsers or existing codebases. By mastering these APIs, you can effectively interact with web servers and handle data with ease.
Additional Resources