How to Send HTTP Requests Using JavaScript

How to Send HTTP Requests Using JavaScript

Nowadays, the interaction between web applications relies on HTTP. For instance, let's say you have an online shop application, and you want to create a new product. You fill in all the necessary information and click Create.

This action will send an HTTP request to the backend, along with all the necessary data, and the backend application will use that data to make changes to the database. After the action is complete, whether successful or not, an HTTP response will be sent back 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 need to follow a certain format so that both ends can understand each other. HTTP was created for this purpose. It is a standard network protocol that enables web applications to understand and communicate with each other.

The HTTP request methods

There are several different methods you could use to send an HTTP request, and each of them serves a different purpose, as shown in the list below:

  • The GET Method

The GET method is used to request data and resources from the server. When you send a GET request, the query parameters are embedded in the URL in name/value pairs like this:

text
1http://example.com/index.html?name1=value1&name2=value2

Note that the question mark (?) marks the beginning of a list of parameters. Each parameter forms a key/value pair (name=value), and the ampersand (&) is used to divide two different parameters.

  • The POST Method

The POST method is used to send data to the server, either adding a new resource or updating an existing resource. The parameters are stored in the body of the HTTP request.

text
1POST /index.html HTTP/1.1
2Host: example.com
3name1=value1&name2=value2
  • The DELETE Method

This method removes a resource from the server.

  • The HEAD Method

The HEAD method works just like GET. Except the HTTP response sent from the server will only contain the head but not the body. Meaning if the server is OK with the request, it will give you a 200 OK response but not the resource you requested. You can only retrieve the resource with the GET method.

This is very useful when you are testing whether the server works. Sometimes, the resource takes a long time to be transmitted, and for testing purposes, you only need a 200 OK response to know that everything works properly.

  • THE PUT Method

The PUT method is used to update existing resources, and it is similar to the POST method, with one small difference.

When you PUT a resource that already exists, the old resource will be overwritten. And making multiple identical PUT requests will have the same effect as making it once.

When you POST identical resources, that resource will be duplicated every time the request is made.

What is the fetch API

For a long time, the JavaScript community has lacked a standard way to send HTTP requests. Some people use XMLHttpRequest, aka AJAX, while others prefer external libraries such as Axios or JQuery.

The fetch API was introduced in 2015 as the modern, simplified, and standard way of making HTTP requests using JavaScript. It is natively supported, so there is no need to install any third-party libraries.

How to send a GET request using JavaScript

The fetch API is promise-based, which means it offers a clean and concise syntax for writing asynchronous operations. For example, this is how you can send a GET request using the fetch API.

javascript
1fetch("https://api.thedevspace.io/users")
2  .then((response) => {
3    // If the response is not 2xx, throw an error
4    if (!response.ok) {
5      throw new Error("Network response was not ok");
6    }
7
8    // If the response is 200 OK, return the response in JSON format.
9    return response.json();
10  })
11  .then((data) => console.log(data)) // You can continue to do something to the response.
12  .catch((error) => console.error("Fetch error:", error)); // In case of an error, it will be captured and logged.

You can also include custom options with the request, such as custom headers, authorization tokens, etc.

javascript
1fetch("https://api.thedevspace.io/users", {
2  headers: {
3    "Content-Type": "application/json",
4    "Authorization": "your-token-here",
5  },
6  credentials: "same-origin",
7})
8  .then(. . .);

How to send a POST request using JavaScript

When sending a POST request, things get a bit more complex because you need to send data to the server with the request body. This could get complicated depending on the kind of data you're sending and your specific use case.

For example, the following code sends JSON data to the backend.

javascript
1fetch("https://api.thedevspace.io/users", {
2  method: "POST",
3  headers: {
4    "Content-Type": "application/json",
5  },
6  body: JSON.stringify({
7    name: "John Doe",
8    email: "johndoe@example.com",
9  }),
10});

A few things you must pay attention here. First of all, you must explicitly specify the request method. If you leave this out, the default GET method will be used.

Also, the request body only accepts string data, so you must use the stringify() method to convert JSON into a string before assigning it to the request body.

This is also why it is important to include the Content-Type header, which lets whoever is on the receiving end know how to parse the request body.

However, things are usually more complex in practice. For example, when working with web forms, instead of JSON, you are likely using the x-www-form-urlencoded form encoding, in which case the request can be sent like this.

The following example assumes you understand what are event handlers.

javascript
1document.addEventListener("DOMContentLoaded", function () {
2  const form = document.querySelector("form");
3  const usernameInput = document.getElementById("username");
4  const emailInput = document.getElementById("email");
5
6  const formData = new URLSearchParams();
7
8  usernameInput.addEventListener("input", function () {
9    formData.set("username", usernameInput.value);
10  });
11
12  emailInput.addEventListener("input", function () {
13    formData.set("email", emailInput.value);
14  });
15
16  form.addEventListener("submit", async function (event) {
17    event.preventDefault(); // Prevent the default form submission action
18
19    await fetch("https://api.thedevspace.io/users", {
20      method: "POST",
21      body: formData.toString(),
22      headers: {
23        "Content-Type": "application/x-www-form-urlencoded",
24      },
25    });
26  });
27});

If you need to upload files to the backend, you'll need the multipart/form-data form encoding instead.

javascript
1document.addEventListener("DOMContentLoaded", function () {
2  const form = document.getElementById("myForm");
3  const usernameInput = document.getElementById("username");
4  const emailInput = document.getElementById("email");
5  const pictureInput = document.getElementById("picture");
6
7  const formData = new FormData();
8
9  usernameInput.addEventListener("input", function () {
10    formData.set("username", usernameInput.value);
11  });
12
13  emailInput.addEventListener("input", function () {
14    formData.set("email", emailInput.value);
15  });
16
17  pictureInput.addEventListener("change", function () {
18    formData.set("picture", pictureInput.files[0]);
19  });
20
21  form.addEventListener("submit", async function (event) {
22    event.preventDefault(); // Prevent the default form submission
23
24    await fetch("https://api.thedevspace.io/users", {
25      method: "POST",
26      body: formData,
27    });
28  });
29});

Note that when using the FormData() to construct the request body, the Content-Type will be locked into multipart/form-data. In this case, it is not necessary to set a custom Content-Type header.

How to send a PUT request using JavaScript

The PUT request works similarly to POST, only you must remember to set method to PUT.

javascript
1fetch("https://api.thedevspace.io/users", {
2  method: "PUT",
3  headers: {
4    "Content-Type": "application/json",
5  },
6  body: JSON.stringify({
7    id: "123"
8    name: "John Doe",
9    email: "johndoe@example.com",
10  }),
11});

Realistically, you will need to provide an id, or any other keys that enable you to locate the record to be updated in the backend.

How to send a DELETE request using JavaScript

The DELETE request works similarly to PUT, only remember to set method to DELETE.

javascript
1fetch("https://api.thedevspace.io/users/123", {
2  method: "DELETE",
3});

And similarly, remember to provide an id, so that the backend application knows which record to delete.

How to send a request using XMLHttpRequest (AJAX)

Besides fetch(), it is also possible to make an HTTP request using XMLHttpRequest. The following example demonstrates how to make a GET request to the endpoint https://api.thedevspace.io/users.

javascript
1var xhr = new XMLHttpRequest();
2xhr.open("GET", "https://api.thedevspace.io/users", true);
3xhr.onload = function () {
4  if (xhr.status >= 200 && xhr.status < 300) {
5    console.log(JSON.parse(xhr.responseText));
6  } else {
7    console.error("Error:", xhr.statusText);
8  }
9};
10xhr.onerror = function () {
11  console.error("Request failed");
12};
13xhr.send();

The syntax is a bit more complex, as XMLHttpRequest relies on callback functions to work with asynchronous operations, which means it is easy to lead to what is known as the callback hell, where you have layers upon layers of callback functions, making your code base difficult to read and maintain.

However, XMLHttpRequest does have some advantages. Due to the fact that XMLHttpRequest is much older compared to fetch(), it is more widely supported. You should consider using XMLHttpRequest when your web app needs to be compatible with older browsers.

How to send a request using external libraries

Aside from the built-in methods, you can also send HTTP requests using third-party libraries. For instance, this is how you can send a GET request using jQuery:

javascript
1$.get("https://api.example.com/data", function (data) {
2  console.log(data);
3}).fail(function (error) {
4  console.error("Error:", error);
5});

jQuery is one of the most popular JavaScript libraries. It aims to fix the part of JavaScript that is difficult to use, and it has been pretty successful at that.

In recent years, jQuery has lost some popularity as vanilla JavaScript has improved over the years and the problems that used to bother people have been fixed. It is no longer the go-to choice for creating JavaScript applications, especially for newer developers.

Alternatively, you could go with Axios, which is a promise-based HTTP client just like fetch(), and it has been people's favorite for a very long time before fetch() came.

javascript
1axios
2  .get("https://api.example.com/data")
3  .then((response) => console.log(response.data))
4  .catch((error) => console.error("Axios error:", error));

Axios and fetch() have very similar syntax as they are both promise-based. The main difference between them is that fetch() is built-in, while Axios requires you to install an external library. However, Axios is much more feature-rich, as it comes with request/response interceptors, automatic JSON handling, and built-in timeouts.

Conclusion

We introduced four different ways you could send HTTP requests using JavaScript in this tutorial. It is up to you to decide which is best for your project.

The fetch API is the modern and standard way of making HTTP requests using JavaScript. It has a relatively simple syntax, which makes your project easier to maintain.

XMLHttpRequest is the legacy method of sending HTTP requests. It is generally not recommended for use in new projects, but if your project needs to be compatible with legacy browsers, XMLHttpRequest might still come in handy.

jQuery is an external package that can do a lot of things, including sending HTTP requests. Although the significance of jQuery has been fading in recent years, it is still used in many older projects, and you might encounter it in your work as a JavaScript developer.

Axios is a third-party library used to send HTTP requests. It has a very similar syntax to the fetch API but comes with a lot more advanced features. It is up to you to decide if you need these features. If not, it is generally recommended to use fetch() instead.

Interested in Learning Web Development?

Starting from HTML, CSS to JavaScript, from language syntaxes to frameworks, from the frontend to the backend, we'll guide you through every step of your coding journey.

Get started from here 🎉