- JavaScript Get Request – How to Make an HTTP Request in JS
- How to Make a GET Request with the Fetch API
- How to Make a GET Request with Axios
- How to Make a GET Request with XMLHttpRequest
- How to Make a GET Request with jQuery
- Wrapping Up
- Here are the most popular ways to make an HTTP request in JavaScript
- Ajax
- jQuery methods
- $.ajax
- $.get method
- $.post
- $.getJSON
- fetch
- Axios
- Usage:
- Making a Request with axios:
- GET:
- POST:
- Angular HttpClient
- Making a call to the server using the Angular HttpClient
- Wrapping Up
JavaScript Get Request – How to Make an HTTP Request in JS
Joel Olawanle
When building applications, you will have to interact between the backend and frontend to get, store, and manipulate data.
This interaction between your frontend application and the backend server is possible through HTTP requests.
There are five popular HTTP methods you can use to make requests and interact with your servers. One HTTP method is the GET method, which can retrieve data from your server.
This article will teach you how to request data from your servers by making a GET request. You will learn the popular methods that exist currently and some other alternative methods.
For this guide, we’ll retrieve posts from the free JSON Placeholder posts API.
There are two popular methods you can easily use to make HTTP requests in JavaScript. These are the Fetch API and Axios.
How to Make a GET Request with the Fetch API
The Fetch API is a built-in JavaScript method for retrieving resources and interacting with your backend server or an API endpoint. Fetch API is built-in and does not require installation into your project.
Fetch API accepts one mandatory argument: the API endpoint/URL. This method also accepts an option argument, which is an optional object when making a GET request because it is the default request.
Let’s create a GET request to get a post from the JSON Placeholder posts API.
fetch("https://jsonplaceholder.typicode.com/posts/1") .then((response) => response.json()) .then((json) => console.log(json));
This will return a single post which you can now store in a variable and use within your project.
Note: For other methods, such as POST and DELETE, you need to attach the method to the options array.
How to Make a GET Request with Axios
Axios is an HTTP client library. This library is based on promises that simplify sending asynchronous HTTP requests to REST endpoints. We will send a GET request to the JSONPlaceholder Posts API endpoint.
Axios, unlike the Fetch API, is not built-in. This means you need to install Axios into your JavaScript project.
To install a dependency into your JavaScript project, you will first initialize a new npm project by running the following command in your terminal:
And now you can install Axios to your project by running the following command:
Once Axios is successfully installed, you can create your GET request. This is quite similar to the Fetch API request. You will pass the API endpoint/URL to the get() method, which will return a promise. You can then handle the promise with the .then() and .catch() methods.
axios.get("https://jsonplaceholder.typicode.com/posts/1") .then((response) => console.log(response.data)) .catch((error) => console.log(error));
Note: The major difference is that, for Fetch API, you first convert the data to JSON, while Axios returns your data directly as JSON data.
At this point, you have learned how to make a GET HTTP request with Fetch API and Axios. But there are some other methods that still exist. Some of these methods are XMLHttpRequest and jQuery.
How to Make a GET Request with XMLHttpRequest
You can use the XMLHttpRequest object to interact with servers. This method can request data from a web server’s API endpoint/URL without doing a full page refresh.
Note: All modern browsers have a built-in XMLHttpRequest object to request data from a server.
Let’s perform the same request with the XMLHttpRequest by creating a new XMLHttpRequest object. You will then open a connection by specifying the request type and endpoint (the URL of the server), then you’ll send the request, and finally listen to the server’s response.
const xhr = new XMLHttpRequest(); xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1"); xhr.send(); xhr.responseType = "json"; xhr.onload = () => < if (xhr.readyState == 4 && xhr.status == 200) < console.log(xhr.response); >else < console.log(`Error: $`); > >;
In the above code, a new XMLHttpRequest object is created and stored in a variable called xhr . You can now access all its objects using the variable, such as the .open() method, when you specify the request type (GET) and the endpoint/URL where you want to request data.
Another method you will use is .send() , which sends the request to the server. You can also specify the format in which the data will be returned using the responseType method. At this point, the GET request is sent, and all you have to do is listen to its response using the onload event listener.
If the client’s state is done (4), and the status code is successful (200), then the data will be logged to the console. Otherwise, an error message showing the error status will appear.
How to Make a GET Request with jQuery
Making HTTP requests in jQuery is relatively straightforward and similar to the Fetch API and Axios. To make a GET request, you will first install jQuery or make use of its CDN in your project:
With jQuery, you can access the GET method $.get() , which takes in two parameters, the API endpoint/URL and a callback function that runs when the request is successful.
$.get("https://jsonplaceholder.typicode.com/posts/1", (data, status) => < console.log(data); >);
Note: In the callback function, you have access to the request’s data and the request’s status.
You can also use the jQuery AJAX Method, which is quite different and can be used to make asynchronous requests:
Wrapping Up
In this article, you have learned how to make the HTTP GET request in JavaScript. You might now begin to think — which method should I use?
If it’s a new project, you can choose between the Fetch API and Axios. Also, if you want to consume basic APIs for a small project, there is no need to use Axios, which demands installing a library.
Here are the most popular ways to make an HTTP request in JavaScript
Said Hayani
JavaScript has great modules and methods to make HTTP requests that can be used to send or receive data from a server side resource. In this article, we are going to look at a few popular ways to make HTTP requests in JavaScript.
Ajax
Ajax is the traditional way to make an asynchronous HTTP request. Data can be sent using the HTTP POST method and received using the HTTP GET method. Let’s take a look and make a GET request. I’ll be using JSONPlaceholder, a free online REST API for developers that returns random data in JSON format.
To make an HTTP call in Ajax, you need to initialize a new XMLHttpRequest() method, specify the URL endpoint and HTTP method (in this case GET). Finally, we use the open() method to tie the HTTP method and URL endpoint together and call the send() method to fire off the request.
We log the HTTP response to the console by using the XMLHTTPRequest.onreadystatechange property which contains the event handler to be called when the readystatechanged event is fired.
const Http = new XMLHttpRequest(); const url='https://jsonplaceholder.typicode.com/posts'; Http.open("GET", url); Http.send(); Http.onreadystatechange = (e) =>
If you view your browser console, it will return an Array of data in JSON format. But how would we know if the request is done? In other words, how we can handle the responses with Ajax?
The onreadystatechange property has two methods, readyState and status which allow us to check the state of our request.
If readyState is equal to 4, it means the request is done. The readyState property has 5 responses. Learn more about it here.
Apart from directly making an Ajax call with JavaScript, there are other more powerful methods of making an HTTP call such as $.Ajax which is a jQuery method. I’ll discuss those now.
jQuery methods
jQuery has many methods to easily handle HTTP requests. In order to use these methods, you’ll need to include the jQuery library in your project.
$.ajax
jQuery Ajax is one of the simplest methods to make an HTTP call.
The $.ajax method takes many parameters, some of which are required and others optional. It contains two callback options success and error to handle the response received.
$.get method
The $.get method is used to execute GET requests. It takes two parameters: the endpoint and a callback function.
$.post
The $.post method is another way to post data to the server. It take three parameters: the url , the data you want to post, and a callback function.
$.getJSON
The $.getJSON method only retrieves data that is in JSON format. It takes two parameters: the url and a callback function.
jQuery has all these methods to request for or post data to a remote server. But you can actually put all these methods into one: the $.ajax method, as seen in the example below:
fetch
fetch is a new powerful web API that lets you make asynchronous requests. In fact, fetch is one of the best and my favorite way to make an HTTP request. It returns a “Promise” which is one of the great features of ES6. If you are not familiar with ES6, you can read about it in this article. Promises allow us to handle the asynchronous request in a smarter way. Let’s take a look at how fetch technically works.
The fetch function takes one required parameter: the endpoint URL. It also has other optional parameters as in the example below:
As you can see, fetch has many advantages for making HTTP requests. You can learn more about it here. Additionally, within fetch there are other modules and plugins that allow us to send and receive a request to and from the server side, such as axios.
Axios
Axios is an open source library for making HTTP requests and provides many great features. Let’s have a look at how it works.
Usage:
First, you’d need to include Axios. There are two ways to include Axios in your project.
Then you’d need to import it
Second, you can include axios using a CDN.
Making a Request with axios:
With Axios you can use GET and POST to retrieve and post data from the server.
GET:
axios takes one required parameter, and can take a second optional parameter too. This takes some data as a simple query.
POST:
Axios returns a “Promise.” If you’re familiar with promises, you probably know that a promise can execute multiple requests. You can do the same thing with axios and run multiple requests at the same time.
Axios supports many other methods and options. You can explore them here.
Angular HttpClient
Angular has its own HTTP module that works with Angular apps. It uses the RxJS library to handle asynchronous requests and provides many options to perform the HTTP requests.
Making a call to the server using the Angular HttpClient
To make a request using the Angular HttpClient, we have to run our code inside an Angular app. So I created one. If you’re not familiar with Angular, check out my article, learn how to create your first Angular app in 20 minutes.
The first thing we need to do is to import HttpClientModule in app.module.ts
Then, we have to create a service to handle the requests. You can easily generate a service using Angular CLI.
ng g service FetchdataService
Then, we need to import HttpClient in fetchdataService.ts service and inject it inside the constructor.
And in app.component.ts import fetchdataService
//import import < FetchdataService >from './fetchdata.service';
Finally, call the service and run it.
You can check out the demo example on Stackblitz.
Wrapping Up
We’ve just covered the most popular ways to make an HTTP call request in JavaScript.
Thank you for your time. If you like it, clap up to 50, click follow, and reach out to me on Twitter.
By the way, I’ve recently worked with a strong group of software engineers for one of my mobile applications. The organization was great, and the product was delivered very quickly, much faster than other firms and freelancers I’ve worked with, and I think I can honestly recommend them for other projects out there. Shoot me an email if you want to get in touch — said@devsdata.com.