JavaScript Today, the interaction between web applications is based on HTTP. For example, let’s say you have an online store application and you want to create a new product. You need to fill out all the necessary information and probably click a button that says “Create.”
This action will send an HTTP request to the backend, along with all the necessary data, and the backend application will use this data to make changes to the database. Once the action is completed, whether successful or not, an HTTP response will be sent to the frontend, which will act accordingly based on the status of that response.
When these requests and responses are transferred back and forth, they must follow a certain format so that both ends can understand each other. HTTP was created for this purpose. It is a standard networking protocol that allows web applications to understand and communicate with each other.
What Are the HTTP Request Methods?
There are several methods you can use to send an HTTP request, and each of them serves a different purpose, as shown below:
The GET method
The GET method is used to request data and resources from the server. When you send a GET request, the request parameters are entrenched in the URL in name/value pairs like this:
Note that the question mark indicates the start of a parameter list. Each parameter forms a key/value pair (name=value), and the ampersand is used to split two different parameters.
The POST method
The POST technique is used to send data to the server, either by adding a new resource or updating an existing resource. The parameters are stowed in the body of the HTTP request.
The DELETE method
This method deletes a reserve from the server.
The HEAD method
The HEAD method works like GET except that the HTTP response sent by the server will only contain the header but not the body. This means that if the server is “OK” with the appeal, it will give you a 200 OK response but not the resource you invited. You can only retrieve the reserve with the GET method.
This is very useful for testing if the server is working. Sometimes, it can take a long time to transmit the resource, and for testing purposes, you only need a 200 OK response to know that everything is working correctly.
The PUT method
The PUT method is cast-off to update existing resources and is similar to the POST method but with a small difference.
When you PUT a resource that already exists, the previous resource will be overwritten. Doing multiple identical PUT requests will have the same effect as doing it just once.
When you PUBLISH identical resources, that resource is duplicated for each request.
What is the recovery API?
For a long time, the JavaScript community lacked a standard way to send HTTP requests. Some people used XMLHttpRequest, also known as AJAX, while others preferred external libraries like Axios or jQuery.
The Fetch API was introduced in 2015 as a modern, simplified, and standard way to make HTTP requests using JavaScript. It is supported natively, so there is no need to install third-party libraries.
How to send a GET request using JavaScript
The Fetch API is promise-based, meaning it provides a clear and concise syntax for writing asynchronous operations. For example, here’s how to send a GET request using the Fetch API.
fetch(“https://jsonplaceholder.typicode.com/users”)
.then((response) =>
{// If the response is not 2xx, throw an error
if (!response. ok) {
throw new Error(“Network response was not ok”);}
{// If the response is 200 OK, return the response in JSON format.
return response.json();})
.then((data) => console.log(data)) // You can continue to do something to the response.
.catch((error) => console. error(“Fetch error,” error)); // In case of an error, it will be captured and logged.
You can also include custom options on request, such as custom headers, authorization tokens, etc.
fetch(“https://jsonplaceholder.typicode.com/users”, {
headers: {
{“Content-Type”: “application/json”,{
{“Authorization”: “your-token-here,”},
{credentials: “same-origin,”})
.then(. . .);
How to Send a POST Request Using JavaScript
When sending a POST request, things get a little more complex because you need to send data to the server along with the request body. This cannot be very easy, depending on the type of data you are sending and your specific use case.
For example, the following code sends JSON data to the backend:
fetch(“https://jsonplaceholder.typicode.com/users”, {
method: “POST”,
headers: {
“Content-Type”: “application/json,”
},
body: JSON.stringify({
name: “John Doe,”
email: “johndoe@example.com,”
}),
});
There are a few things you should pay attention to here. First, you must explicitly specify the query method. If you omit this, the default GET method will be used.
Additionally, the request body only accepts string data, so you must use the stringify() method to convert JSON to a string before assigning it to the request body.
That’s why it’s also important to include the Content-Type header, which lets the recipient know how to parse the request body.
But in practice, things are often more complex. For example, when working with web forms, instead of JSON, you are probably using x-www-form-urlencoded form encoding, in which case the request can be sent like this.
The following example assumes that you understand what event handlers are.
Document.addEventListener(“DOMContentLoaded,” function () {
const form = document.querySelector(“form”);
const usernameInput = document.getElementById(“username”);
const emailInput = document.getElementById(“email”);
const formData = new URLSearchParams();
username input.addEventListener(“input,” function () {
formData.set(“username”, usernameInput.value);
});
emailInput.addEventListener(“input”, function () {
formData.set(“email”, emailInput.value);
});
form.addEventListener(“submit,” async function (event) {
event.preventDefault(); // Prevent the default form submission action
await fetch(“https://jsonplaceholder.typicode.com/users”, {
method: “POST,”
body: formData.toString(),
headers: {
“Content-Type”: “application/x-www-form-urlencoded,”
},
});
});
});
If you need to upload files to the backend, you will need a multipart form/form-data encoding.
Document.addEventListener(“DOMContentLoaded,” function () {
const form = document.getElementById(“myForm”);
const usernameInput = document.getElementById(“username”);
const emailInput = document.getElementById(“email”);
const pictureInput = document.getElementById(“picture”);
const formData = new FormData();
username input.addEventListener(“input,” function () {
formData.set(“username”, usernameInput.value);
});
emailInput.addEventListener(“input”, function () {
formData.set(“email”, emailInput.value);
});
pictureInput.addEventListener(“change”, function () {
formData.set(“picture”, pictureInput.files[0]);
});
form.addEventListener(“submit,” async function (event) {
event.preventDefault(); // Prevent the default form submission
await fetch(“https://jsonplaceholder.typicode.com/users”, {
method: “POST”,
body: formData,
});
});
});
Note that when FormData() is used to construct the request body, the content type will be locked to multipart/form-data. In this case, there is no need to configure a custom content type header.
How to Send a PUT Request Using JavaScript
The PUT request works the same as POST, but you must remember to set the method to PUT.
fetch(“https://jsonplaceholder.typicode.com/users”, {
method: “PUT”,
headers: {
“Content-Type”: “application/json,”
},
body: JSON.stringify({
id: “123”
name: “John Doe,”
email: “johndoe@example.com,”
}),
});
In fact, you will need to provide an identifier or another key that will allow you to locate the best that will be updated in the backend.
How to Send a DELETE Request Using JavaScript
The DELETE query works the same as PUT, but remember to set the method to DELETE.
fetch(“https://jsonplaceholder.typicode.com/users/123”, {
method: “DELETE”,
});
Similarly, don’t forget to provide an ID so that the backend application knows which record to delete.
How to Send a Request Using XMLHttpRequest (AJAX)
In addition to fetch(), it is also possible to make an HTTP request using XMLHttpRequest. The following example shows how to send a GET request to the endpoint
var xhr = new XMLHttpRequest();
xhr.open(“GET”, “https://jsonplaceholder.typicode.com/users”, true);
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
console.log(JSON.parse(xhr.responseText));
} else {
console.error(“Error:”, xhr.statusText);
}
};
xhr.onerror = function () {
console.error(“Request failed”);
};
xhr.send();
The syntax is a bit more complex, because XMLHttpRequest relies on callback functions to work with asynchronous operations, which means it’s easy to lead to so-called callback hell, where you have layers and layers of callback functions, making your code base difficult to maintain. maintain. . read. and guard.
However, XMLHttpRequest has some advantages. Since XMLHttpRequest is much older than fetch(), it has broader support. It would help if you considered using XMLHttpRequest when your web application needs to be compatible with older browsers.
How to Send a Request Using External Libraries
In adding to the built-in methods, you can also send HTTP requests using third-party libraries. For example, here’s how to send a GET request using jQuery:
$.get(“https://api.example.com/data,” function (data) {
console.log(data);
}).fail(function (error) {
console.error(“Error:”, error);
});
jQuery is one of the most general JavaScript libraries. It aims to fix the part of JavaScript that is difficult to use, and it has achieved this quite well.
In recent years, jQuery has lost some popularity as JavaScript has improved over the years, and the issues that bothered people have been fixed. It is no longer the ideal choice for creating JavaScript applications, especially for new developers.
Alternatively, you can go with Axios, which is a promise-based HTTP client like fetch(), and it has been a people’s favorite for a long time before fetch() came along.
Axios
.get(“https://api.example.com/data”)
.then((response) => console.log(response.data))
.catch((error) => console.error(“Axios error:”, error));
Axios and fetch() have very similar syntax because they are both based on promises. The main difference between them is that fetch() is built-in, while Axios requires you to install an external library. However, Axios has many other features, such as request/response interceptors, automatic JSON handling, and built-in timeouts.
Conclusion
In this tutorial, we cover four different ways to send HTTP requests using JavaScript. It’s up to you to decide which one best suits your project.
Fetch API is the modern, standard way to make HTTP requests using JavaScript. It has a relatively simple syntax, which makes your project easier to maintain.
XMLHttpRequest is the inherited method for sending HTTP requests. It is generally not recommended for use in new projects, but if your project needs to be compatible with existing browsers, XMLHttpRequest can still be useful.
jQuery is an external package that can do many things, including sending HTTP requests. Although jQuery’s importance has decreased in recent years, it is still used in many older projects, and you may encounter it in your work as a JavaScript developer.
Axios is a third-party library used to send HTTP requests. Its syntax is very similar to the Recovery API but has much more advanced functionality. It’s up to you if you need these features. Otherwise, it is generally recommended to use fetch() instead.