HTTP Requests in Javascript
September 15, 2019    |    APIs    |    Basics    |    HTTP

Introduction

Javascript is the scripting language of the web, and so it makes sense for javascript to have built-in APIs for making HTTP requests. In this post, we will look at AJAX and why HTTP requests in Javascript are important. Also, we will look at different ways of making an HTTP request using Fetch API, Axios, XMLHttpRequest and jQuery.

Audience

You should be familiar with the Javascript programming language and understand the basic concepts of HTTP.

Background

When developers talk about HTTP requests in Javascript, they commonly refer to it as AJAX. AJAX stands for Asynchronous Javascript and XML.[1] The term AJAX is essentially synonymous with “HTTP in Javascript”, however, the terms used, such as XML, refer to a markup language used to describe data used in early information exchange before HTML. Although the United States Postal Service still uses XML with its APIs, JSON is now the most common way to exchange data via HTTP requests in Javascript. (The terms Ajax and HTTP Request will be used as synonyms in this article.)

Why is making HTTP requests in Javascript is important?

Web Applications

If you are making a web application you will need to understand how to make HTTP requests. The data you access will probably be accessed via a REST API. Web applications use HTTP request in Javascript to make websites more interactive. For example, when you click the like button on Facebook, an HTTP request is made to Facebook’s server to save the information.

Website Content

Websites often use Javascript to make HTTP requests to load data or update content on a page. Using HTTP requests to load content into a page makes the page load faster because it only needs to load part of the page. This speedy update makes for better user experience.

Next, we’ll look at examples of HTTP request examples.

What are some ways to make HTTP request in Javascript?

There are many ways to make HTTP requests with Javascript. Here are some basic examples of making HTTP requests using several technologies. These examples use the most common request methods GET and POST.

The following examples use JSONPlaceholder to illustrating the HTTP requests.

Fetch API

The preferred way to make HTTP requests in javascript is by using the Fetch API. The fetch API makes it easy to fetch JSON APIs via REST, or even download images or open audio streams from files on the internet.

Fetch API – GET Request

fetch('https://jsonplaceholder.typicode.com/users')
.then(res.json())
.then(data => {
  // data is now a JSON object with users
  console.log(data)
})

Fetch API – POST Request

With a Fetch POST, you add a second parameter after the URI that contains information about the request along with additional headers and data.

Add this object to the Fetch request to make it a POST request:

{
  method: 'POST',
  body: JSON.stringify({
    title: 'HTTP Requests in Javascript',
    body: 'Example body',
    userId: 45
  }),
  headers: {
    "Content-type": "application/json; charset=UTF-8"
  }
}

Full Fetch POST request:

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  body: JSON.stringify({
    title: 'HTTP Requests in Javascript',
    body: 'Example body',
    userId: 45
  }),
  headers: {
    "Content-type": "application/json; charset=UTF-8"
  }
})
.then(res => res.json())
.then(json => {
  console.log('json',json)
})

For more detailed information about the Fetch API read the spec https://fetch.spec.whatwg.org/ or check out my favorite reference from David Walsh https://davidwalsh.name/fetch.

XMLHttpRequest

XMLHttpRequest is the original way HTTP requests were made in Javascript. The method is still available for use today. The code seems a little convoluted compared to Fetch, but in fact, using XMLHttpRequest is fast than fetch because it does not follow the Fetch API specification CORS pre-flight requests.

XMLHttpRequest – GET Request

function httpGet(url, callback) {
  let httpRequest = new XMLHttpRequest();
  httpRequest.onreadystatechange = function() {
    if (httpRequest.readyState === XMLHttpRequest.DONE) {
      if (httpRequest.status === 200) {
        callback(httpRequest.responseText);
      }
    }
  }
  httpRequest.open('GET', url, false);
  httpRequest.send();
}
httpGet('https://jsonplaceholder.typicode.com/users', (data) => {
  console.log('httpGet', JSON.parse(data))
})

XMLHttpRequest – POST Request

function httpPost(url, params, callback) {
  httpRequest = new XMLHttpRequest();
  httpRequest.onreadystatechange = function() {
    if (httpRequest.readyState === XMLHttpRequest.DONE) {
      if (httpRequest.status === 201) {
        callback(httpRequest.responseText);
      }
    }
  }
  httpRequest.open('POST', url);
  httpRequest.setRequestHeader("body", JSON.stringify(params));
  httpRequest.setRequestHeader("Content-type", "application/json; charset=UTF-8");
  httpRequest.send();
}

let uri = 'https://jsonplaceholder.typicode.com/posts';
let postObject = {
  title: 'HTTP Requests in Javascript',
  body: 'Example body',
  userId: 45
};
httpPost(uri, postObject, function(response) {
  console.log('httpPost', JSON.parse(response))
})

For more information on XMLHttpRequests checkout the MDN docs: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest.

jQuery

Before the Fetch API became a standard API in the browser, jQuery was the go-to library for simplifying AJAX requests (among MANY other things.) I recommend checking out jQuery in general. jQuery solves many problems by simplifying the use of browser APIs by making those APIs work in all web browsers through a single method. HTTP request like the XMLHttpRequest’s are complex and also difficult to make work in all web browsers because browser vendors don’t follow the Javascript specification to the T.

jQuery – GET Request

let uri = 'https://jsonplaceholder.typicode.com/users';
jQuery.get(uri, function(response) {
  console.log(response)
});

Notice the difference?

jQuery – POST Request

let uri = 'https://jsonplaceholder.typicode.com/users';
let params = {
  title: 'HTTP Requests in Javascript',
  body: 'Example body',
  userId: 45
}
jQuery.post(uri, params, function(response) {
  console.log(response
});

jQuery makes HTTP/AJAX requests easy to read and write. Head over to the jQuery docs for the full API https://api.jquery.com/category/ajax/.

Axios

The most popular library for making HTTP requests in Javascript is Axios. Axios works in the web browser and in Node for server-side HTTP requests. In addition, Axio adds features that go beyond the Fetch API that include canceling and intercepting requests and automatically converting JSON responses to JSON. Axios provides an easy-to-use HTTP API like jQuery.

AXIOS – GET Request

axios.get('https://jsonplaceholder.typicode.com/users').then((response) => {
  console.log(response)
})

AXIOS – POST Request

axios.post('https://jsonplaceholder.typicode.com/posts', {
  title: 'HTTP Requests in Javascript',
  body: 'Example body',
  userId: 45
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});

Conclusion

This post we looked at HTTP Requests in Javascript, also known as AJAX. Making HTTP requests allows you to make your website more dynamic and fast by updating your website content on the fly. Although older APIs such as XMLHttpRequest are still available in web browsers, you should use the simpler Fetch API or Axios library for making HTTP requests.

I hope you understand more about HTTP in Javascript.

Thanks for reading!

References

  1. “Ajax (programming)”. https://en.wikipedia.org/wiki/Ajax_(programming). Retrieved 2019-09-15.

Was this article helpful?

Comments are closed.