The interaction between the frontend and backend of websites is made possible through HTTP requests. Functionalities like updating a new/old user in a database, publishing a blog post from your WordPress dashboard, deleting a picture from your profile, and updating your bio all require an interaction between a server and a client to modify data.

When building web applications — both frontend and full stack web apps — we often interact with data stored on different databases and servers. These servers may belong to third parties or may be created by the developers of a project.

To interact with these servers, we can make use of different HTTP methods to request for data. We can create, read, update, and delete (or CRUD) data on servers using dedicated HTTP verbs like POST, GET, PUT/PATCH, and DELETE.

In this tutorial, you’ll learn the various ways in which you can make HTTP requests to remote servers and perform CRUD operations in JavaScript.

Each section will introduce a new method for sending HTTP requests. We’ll start from the built-in methods like the fetch API and the XMLHttpRequest object before looking at some open-source HTTP request libraries like Axios and SuperAgent.

Let’s get started!

What Is a JavaScript HTTP Request?

HTTP requests in JavaScript are a set of predefined methods used for interacting with data stored on servers.

Every request sent to a server includes an endpoint and the type of request being sent. You can see an endpoint as a gateway between two programsː the client and the server.

The client is the program that sends a request while the server is the one that receives the request. The server sends back a response depending on the validity of the request. If the request is successful, the server sends back data in either XML or JSON format (JSON in most cases), and if the request fails, the server sends back an error message.

Responses sent back by the server are usually associated with status codes. These codes help us understand what the server is trying to say when it receives a request. Here are some of them and what they mean:

  • 100–199 denotes an informational response.
  • 200–299 denotes a successful request.
  • 300–399 denotes redirection.
  • 400–499 denotes client error.
  • 500–599 denotes server error.

We’ll talk more about some of these in the sections that follow.

In the next section, you’ll see the different ways that you can make HTTP requests in JavaScript.

How To Make an HTTP Request in JavaScript

This section will be divided into sub-sections, each section teaching you different methods you can use to make HTTP requests in JavaScript.

Each method discussed will have an example showing how to send POST, GET, PUT/PATCH, and DELETE requests to servers.

JSON Placeholder will serve as the remote server/endpoint where all our requests will be sent.

Let’s dive in!

1. How To Make an HTTP Request in JavaScript Using XMLHttpRequest (AJAX)

XMLHttpRequest is a built-in JavaScript object used for interacting with servers and loading content in web pages without reloading the browser.

In this section, you’ll see how to send POST, GET, PUT/PATCH, and DELETE requests using XMLHttpRequest.

AJAX is used to make asynchronous HTTP requests. This simply means that while a response from a request is pending, other parts of your JavaScript code can continue running without waiting for the request to complete first.

You can also push modifications to a particular section of your web page without forcing the visitor to reload the whole page by using AJAX.

AJAX, by default, works with the XMLHttpRequest object, so the examples in this section can be considered as AJAX requests.

How To Send a GET Request in JavaScript Using XMLHttpRequest

You make use of the GET request when you want to retrieve data from a server. To send a successful GET request using XMLHttpRequest in JavaScript, you should ensure that the following are done correctly:

  1. Create a new XMLHttpRequest object.
  2. Open a connection by specifying the request type and endpoint (the URL of the server).
  3. Send the request.
  4. Listen for the server’s response.

Now that we’ve seen some of the steps involved in sending a POST request using XMLHttpRequest, let’s see a code exampleː

const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/users");
xhr.send();
xhr.responseType = "json";
xhr.onload = () => {
  if (xhr.readyState == 4 && xhr.status == 200) {
    const data = xhr.response;
    console.log(data);
  } else {
    console.log(`Error: ${xhr.status}`);
  }
};

We’ll break down the code above to help you understand what’s happening here.

The first thing we did was create a new XMLHttpRequest object and store it in a variable called xhr. That is:

const xhr = new XMLHttpRequest();

We then specified the request type (GET) and the endpoint where the request will be sent to (in this case, “https://jsonplaceholder.typicode.com/users“)ː

xhr.open("GET", "https://jsonplaceholder.typicode.com/users");

In order to send the request to the server, we used the send() method.

When the server sends back data, you can specify the format in which the data is returned.

In most cases, JSON is used. So we made sure our data was returned in JSON by adding this:

xhr.responseType = "json";

At this point, we have successfully sent a GET request. The next thing to do is to listen to what the server says by using an event listener:

xhr.onload = () => {
  if (xhr.readyState == 4 && xhr.status == 200) {
    const data = xhr.response;
    console.log(data);
  } else {
    console.log(`Error: ${xhr.status}`);
  }
};

In the code above, we’re making use of the onload event listener. Using an if statement, we checked the status of the server’s response.

If the state of the client is 4 (DONE) and if the status code is 200 (successful), the data will be logged to the console. Otherwise, an error message showing the error status will appear.

If you’ve followed up to this point without any errors, you should have an array of objects in your consoleː

[{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

This is the data retrieved from the server.

How To Send a POST Request in JavaScript Using XMLHttpRequest

With the POST request, you can send new information (data) to the server/database as an object. The object could be information about a new user, a new to-do list entry, or whatever else you need to log.

The code example you’ll see in this section is similar to the one in the last section. The main difference is that POST requests require some information which is usually stored in an object before it is sent to the server.

Here’s an example:

const xhr = new XMLHttpRequest();
xhr.open("POST", "https://jsonplaceholder.typicode.com/posts");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
const body = JSON.stringify({
  title: "Hello World",
  body: "My POST request",
  userId: 900,
});
xhr.onload = () => {
  if (xhr.readyState == 4 && xhr.status == 201) {
    console.log(JSON.parse(xhr.responseText));
  } else {
    console.log(`Error: ${xhr.status}`);
  }
};
xhr.send(body);

In the code above, the information to be sent to the server is stored in a variable called body. It holds three propertiesː title, body, and userId.

Note that the body variable which holds the object must be converted to a JSON object before it’s sent to the server. The conversion is done using the JSON.stringify() method.

To make sure the JSON object is sent to the server, it’s passed in as a parameter to the send() method:

xhr.send(body);

How To Send a PATCH Request in JavaScript Using XMLHttpRequest

The PATCH request is used to update specified properties of an object. This is different from the PUT method, which updates the entirety of an object.

Here’s an example of a PATCH request using XMLHttpRequest in JavaScript:

const xhr = new XMLHttpRequest();
xhr.open("PATCH", "https://jsonplaceholder.typicode.com/posts/101");
xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
const body = JSON.stringify({
  body: "My PATCH request",
});
xhr.onload = () => {
  var data = JSON.parse(xhr.responseText);
  if (xhr.readyState == 4 && xhr.status == "200") {
    console.log(data);
  } else {
    console.log(`Error: ${xhr.status}`);
  }
};
xhr.send(body);

The code above, if successful, will log the part of the object that was updated and sent to the server.

How To Send a DELETE Request in JavaScript Using XMLHttpRequest

Just like the name implies, the DELETE method is used to delete data from a server. This is the same for any JavaScript HTTP method.

In most cases, you’ll have to specify the ID of the data you want to delete. The ID is usually a parameter in the endpoint/URL.

Let’s see an example of a DELETE requestː

const xhr = new XMLHttpRequest();
xhr.open("DELETE", "https://jsonplaceholder.typicode.com/posts/3");
xhr.onload = function () {
  var data = JSON.parse(xhr.responseText);
  if (xhr.readyState == 4 && xhr.status == "200") {
    console.log(data);
  } else {
    console.log(`Error: ${xhr.status}`);
  }
};
xhr.send();

The code above will delete an object with a post with an ID of 3 as specified in the endpoint (“https://jsonplaceholder.typicode.com/posts/3“).

2. How To Make an HTTP Request in JavaScript Using jQuery

jQuery simplifies the process of getting data from servers by making the syntax shorter and more straightforward.

In this section, you’ll see how to make HTTP requests using different jQuery methods.

How To Send a GET Request in JavaScript Using jQuery

jQuery provides us with the $.get() method for sending GET requests to servers. The method takes in two parameters — the URL to the server and a callback function which runs if the request is successful.

Here’s an example:

$.get("https://jsonplaceholder.typicode.com/users", (data, status) => {
  console.log(data);
});

As can be seen in the code above, the $.get() method took in the URL (https://jsonplaceholder.typicode.com/users) and an anonymous callback function as its parameters.

Through the callback function, you can access the data from the request and the status of the request. In our own case, we logged the data to the console.

That’s how simple it is to send a GET request using jQuery.

How To Send a POST Request in JavaScript Using jQuery

To send a POST request using jQuery, we use the $.post() method. It takes three parameters — the URL, the data to be sent to the server, and a callback function.

const body = JSON.stringify({
  title: "Hello World",
  body: "My POST request",
  userId: 900,
});
$.post("https://jsonplaceholder.typicode.com/users", body, (data, status) => {
  console.log(data);
});

In the code above, we created an object to be sent to the server and stored it in a variable called body. This variable was passed in as a second parameter in the $.post() method.

Using the callback function, we logged the result of the request to the console.

3. How To Make Asynchronous Requests in jQuery Using the $.ajax() Method

Before we proceed to sending PATCH and DELETE requests, let’s talk about the $.ajax() method.

The $.ajax() method in jQuery is used to make asynchronous requests.

The syntax is different from the others.

Here’s how you’d make a GET request using the $.ajax() method:

$.ajax({
  url: "https://jsonplaceholder.typicode.com/users",
  type: "GET",
  success: function (result) {
    console.log(result);
  },
});

The $.ajax() method has different parameters that we can use.

In the code above, the url parameter specifies the URL to the server, the type specifies the request type, and the success parameter calls a callback function if the request is successful.

In the next section, you’ll see how to send PATCH and DELETE requests using jQuery’s $.ajax() method.

How To Send a PATCH Request in JavaScript Using jQuery’s $.ajax() Method

In this section, you’ll see how to send PATCH requests using jQuery’s $.ajax() method.

Here’s the code:

const body = JSON.stringify({
  body: "My PATCH request",
});
$.ajax({
  url: "https://jsonplaceholder.typicode.com/posts/101",
  type: "PATCH",
  data: body,
  success: function (result) {
    console.log(result);
  },
});

In the code above, the property to be updated is stored in the body variable. This is then used as the value for the data parameter.

If the request is successful, the function for the success parameter will be executed.

How To Send a DELETE Request in JavaScript Using jQuery’s $.ajax() Method

Sending a DELETE request using jQuery’s $.ajax() method only requires a few lines of code.

Here’s an example:

$.ajax({
  url: "https://jsonplaceholder.typicode.com/posts/3",
  type: "DELETE",
  success: function (result) {
    console.log(result)
  },
});

As can be seen above, all we had to do was specify the URL with the ID of the object to be deleted, the type of request, and a function that runs if the request is successful.

How To Use the $.getJSON Method in jQuery

The $.getJSON method provides a shorter way of sending GET requests.

To make a successful request, you just have to specify the URL and the callback function. Here’s an example:

$.getJSON("https://jsonplaceholder.typicode.com/users", function (result) {
  console.log(result)
});

In the code above, we passed in the URL to the server and the function that runs after the request succeeds as parameters to the $.getJSON method.

The code above will log an array of objects containing user information to the console.

4. How To Make an HTTP Request in JavaScript Using the Fetch API

The fetch API is one of the most popular ways of interacting with servers using JavaScript. It is a native JavaScript API which has support for promises while making requests.

The syntax for using the fetch API is very easy to understand, as you’ll see in the sections that follow.

How To Send a GET Request in JavaScript Using the Fetch API

Sending a GET request using the fetch API only requires the URL. This then returns a promise which you can access using the then() method or the async and await keywords.

Let’s look at an example:

fetch("https://jsonplaceholder.typicode.com/posts")
.then((response) => response.json())
.then((json) => console.log(json));

In the code above, we passed in the URL to the fetch method; this returns a promise. We then accessed the server’s response using the then() method. The response was converted into a JSON object using the response.json() method.

After getting the response, we then used another then() method to log out the data to the console.

How To Send a POST Request in JavaScript Using the Fetch API

The fetch method has a second parameter that allows us to specify body (data to be sent) and type of request to be sent. This second parameter lets us send POST and PATCH requests.

Take a look at this sample code:

fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "POST",
  body: JSON.stringify({
    title: "Hello World",
    body: "My POST request",
    userId: 900,
  }),
  headers: {
    "Content-type": "application/json; charset=UTF-8",
  },
})
.then((response) => response.json())
.then((json) => console.log(json));

In the code above, we added request options in the fetch method’s second parameter. method was used to specify the request type, body specified the data to be sent to the server, and headers was used to specify that we’d be sending JSON data to the server.

As we did before when sending a GET request, the promise/response returned was accessed using the then() method.

How To Send a PUT Request in JavaScript Using the Fetch API

In other sections where we sent a request to update an object in the server, we made use of PATCH. In this section, we’ll use PUT, which lets you update the entirety of an object.

Here’s an example using the fetch API:

fetch("https://jsonplaceholder.typicode.com/posts/1", {
  method: "PUT",
  body: JSON.stringify({
    id: 1,
    title: "My PUT request",
    body: "Updating the entire object",
    userId: 1,
  }),
  headers: {
    "Content-type": "application/json; charset=UTF-8",
  },
})
.then((response) => response.json())
.then((json) => console.log(json));

Since we’re sending a PUT request, we are required to provide the data to be updated, which gets passed as a value to the body request option.

We also specified the ID of the object to be updated as the last parameter in the URL. If the request runs successfully, you should see the updated object logged to the console.

How To Send a DELETE Request in JavaScript Using the Fetch API

Sending a DELETE request is pretty straightforward — all you have to do is to specify the ID of the object to be deleted. You can use the then() method to receive the response from the server, like we did with the other requests.

Here’s a quick example:

fetch("https://jsonplaceholder.typicode.com/posts/3", {
  method: "DELETE",
});

The code above will delete an object with an ID of 3.

5. How To Make an HTTP Request in JavaScript Using Axios

Axios is a third party promise-based library for sending HTTP requests. Just like most modern HTTP clients, it simplifies the process involved in sending requests to a server.

In this section, you’ll learn how to send GET, POST, PUT, and DELETE requests to a server using Axios.

Note that Axios is not built into JavaScript — you’ll have to install it separately to make use of its functionality. To install Axios in your project, run the command below in your project terminal:

npm install axios

How To Send a GET Request in JavaScript Using Axios

To send a GET request using Axios, you just have to pass in the URL to the get() method, which returns a promise. The response returned from the promise can be accessed using the then() method.

Let’s see an example:

axios.get("https://jsonplaceholder.typicode.com/posts")
.then((response) => console.log(response.data))
.catch((error) => console.log(error));

The code above will log out an array of objects containing data returned from the server. You’d notice that we didn’t have to change the returned objects to JSON objects — Axios handles this under the hood, and you can access the data using response.data.

To catch any errors, we used the catch() method.

How To Send a POST Request in JavaScript Using Axios

The POST request in Axios takes two parameters — the URL and the data to be sent to the server. You can store the data in a variable or pass it directly as a parameter.

Here’s how:

axios.post("https://jsonplaceholder.typicode.com/posts", {
  title: "POST request with Axios",
  body: "POST request",
  userId: 10,
})
.then(function (response) {
  console.log(response.data);
})
.then((error) => console.log(error))

In the example above, we’re sending data to the server. The data is passed in as a second parameter to the post() method.

If the request is sent successfully, you’d see the result logged to the console.

How To Send a PUT Request in JavaScript Using Axios

Sending a PUT request with Axios is similar to sending a POST request. To send a PUT request, you specify the URL (including the ID of the object to be updated) and the data to be updated as a second parameter in the put() method.

The example below will update an object with an ID of 10:

axios.put("https://jsonplaceholder.typicode.com/posts/10", {
  title: "PUT request with Axios",
  body: "PUT request",
  userId: 10,
})
.then(function (response) {
  console.log(response.data);
})
.then((error) => console.log(error))

How To Send a DELETE Request in JavaScript Using Axios

To send a DELETE request, you specify the ID of the object to be deleted in the URL.

As usual, you have to specify the URL along with the ID of the object to be deleted.

Here’s an example:

axios.delete("https://jsonplaceholder.typicode.com/posts/10")
.then(function (response) {
  console.log(response);
})
.then((error) => console.log(error))

6. How To Make an HTTP Request in JavaScript Using SuperAgent

SuperAgent is one of the oldest libraries built for making HTTP requests in JavaScript. Just like Axios, it supports promises and has prebuilt methods for sending various HTTP requests to servers.

To use SuperAgent, install it using the command below:

npm install superagent

We’ll start with a GET request example.

How To Send a GET Request in JavaScript Using SuperAgent

SuperAgent provides us with a get() method for sending GET requests. The URL is passed in as the method’s parameter.

The promise returned from the request can then be assessed using the end() method, as seen in this example:

superagent
.get("https://jsonplaceholder.typicode.com/posts")
.end((error, response) => {
  console.log(response.body);
});

How To Send a POST Request in JavaScript Using SuperAgent

When sending a POST request using SuperAgent, you pass in the data to be sent to the server as a parameter to SuperAgent’s send() method:

superagent
.post("https://jsonplaceholder.typicode.com/posts")
.send({
  title: "POST request with SuperAgent",
  body: "POST request",
  userId: 10,
})
.set("X-API-Key", "foobar")
.set("accept", "json")
.end((err, res) => {
  console.log(res.body);
});

In the code above, the URL was passed in as the post() method’s parameter. The data to be sent was passed into the send() method. Using the end() method, we got the result of the server’s response.

How To Send a PUT Request in JavaScript Using SuperAgent

You can send a PUT request in SuperAgent using the put() method. Just like the example in the last section, the data to be updated would be passed in as a parameter to the send() method.

Here’s an example:

superagent
.put("https://jsonplaceholder.typicode.com/posts/10")
.send({
  title: "PUT request with SuperAgent",
  body: "PUT request",
  userId: 10,
})
.set("X-API-Key", "foobar")
.set("accept", "json")
.end((err, res) => {
  console.log(res.body);
});

How To Send a DELETE Request in JavaScript Using SuperAgent

To send a delete request, you simply specify the ID of the object to be deleted in the URL. This will be used as a parameter in the delete() method.

superagent
.delete("https://jsonplaceholder.typicode.com/posts/10")
.end((err, res) => {
  console.log(res.body);
});

7. How To Make an HTTP Request in JavaScript Using Qwest

Qwest is an AJAX library for interacting with servers. It is currently archived on GitHub — the creator discontinued maintenance of the library with the emergence of the fetch API and Axios.

Qwest also supports the use of promises.

In the following subsections, you’ll see how to send GET, POST, PUT, and DELETE requests using Qwest.

How To Send a GET Request in JavaScript Using Qwest

Qwest has a get() method that can be used to send GET requests. Here’s how to use it:

qwest.get("https://jsonplaceholder.typicode.com/posts")

.then((xhr, response) => console.log(response));

How To Send a POST Request in JavaScript Using Qwest

As a second parameter, the data to be sent to a server will be passed in to the post() method. The first parameter is the URL.

Here’s an example:

qwest.post("https://jsonplaceholder.typicode.com/posts", {
  title: 'POST request with Qwest',
  body: 'POST request',
  userId: 30
})
.then(function(xhr, response) {
  console.log(response)
})
.catch(function(e, xhr, response) {
  console.log(e)
});

How To Send a PUT Request in JavaScript Using Qwest

The syntax here is the same as the one in the previous section. All you have to change is the request type and then specify the ID of the object to be updated along with the data you want to update the object with.

Take a look at this example:

qwest.put("https://jsonplaceholder.typicode.com/posts/30", {
  title: 'PUT request with Qwest',
  body: 'PUT request',
  userId: 30
})
.then(function(xhr, response) {
  console.log(response)
})
.catch(function(e, xhr, response) {
  console.log(e)
});

Note that the ID is being specified in the URL and not in the object being sent to the server.

How To Send a DELETE Request in JavaScript Using Qwest

As usual, to delete an object from a server, you have to specify the URL and the ID of the object to be deleted. Both the URL and ID of the object to be deleted will be passed in as a parameter to the delete() method in Qwest.

Here’s an example:

qwest.delete("https://jsonplaceholder.typicode.com/posts/30")
.then(function(xhr, response) {
  console.log(response)
})
.catch(function(e, xhr, response) {
  console.log(e)
});

Once the request runs successfully, an object with the ID of 30 will be deleted.

Summary

Our ability to interact with servers using JavaScript has evolved over the years. With a growing and active community of JavaScript developers, constant changes are still being made and new tools introduced to make the process simpler and easier.

The methods discussed in this tutorial don’t only apply to remote servers — they can also be used to interact with your own servers when building full stack web applications. They work with numerous JavaScript libraries and frameworks, too.

In this tutorial, we’ve taught you how to make HTTP requests in JavaScript. We gave various examples and explanations that showed how to send GET, POST, PUT/PATCH, and DELETE requests using in-built JavaScript methods and third party libraries.

Building and deploying a website can be a tedious task irrespective of your skillset. But Kinsta makes this easy and effortless with DevKinsta. Used by over 25,000 developers, web designers and freelancers, DevKinsta offers a local environment for developing WordPress themes, plugins, and more. Check it out!