Searching how to make JavaScript HTTP request and get data in JSON format? In this tutorial, you will learn how to make synchronous and asynchronous HTTP requests using plain/vanilla JavaScript.

If you are new to programming and want to get JavaScript Help from an expert feel free to drop us a message.

Synchronous : JavaScript HTTP Request

Below are the steps to make a synchronous HTTP request.

  1. Firstly, make an object of XMLHttpRequest Class.
  2. set responseType to ‘text’ or ‘ ‘.
  3. Create an anonymous function on onreadystatechange.
  4. Check the status and readyState are successful.
  5. On successful .. do something. For example, log the responseText to console or write it to DOM.
  6. Invoke open() function and pass ‘request type’ and the ‘API URL for fetching the data.
  7. Finally, invoke the send() function.

HTTP GET Request using JavaScript Example

For this demo, we will make use of JSONPlaceholder dummy API.



//let XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

let xhr= new XMLHttpRequest();

xhr.responseType='';
xhr.onreadystatechange=()=>{

  if(xhr.status==200 && xhr.readyState==4){
    console.log(JSON.parse(xhr.responseText));
  }

};

let url="https://jsonplaceholder.typicode.com/todos/1"; 

xhr.open('GET',url);
xhr.send();

JavaScript HTTP Request in Browser

You can run the above code in any browser console. And see the JSON response.

Running in Chrome

JavaScript Http request JSON in chrome browser

JavaScript Http request JSON in chrome browser

We tested the code in the chrome browser and were getting few errors initially such as

  • net::ERR_FAILED
  • XHR failed loading: GET “https://…

later on, after debugging we got to know that we need to open localhost in the URL(browser) or any domain. Then open the browser console and execute the code to see the HTTP request in JSON format.

ReferenceError: XMLHttpRequest is not defined | Node.js Error

If you are using Node.js and executing the above code you might get ReferenceError: XMLHttpRequest is not defined. To resolve this error.

  1. You need to install the xmlhttprequest module from npm. Command:  npm install xmlhttprequest --save
  2. And then declare XMLHttpRequest at the very first line. let XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
  3. Re-run the code.

We were also getting the same ReferenceError: XMLHttpRequest is not defined when we first tried to execute the code in Node.js.

xhr.responseText console.log javascript

AJAX HTTP request in node.js

Further, if you want to make an asynchronous HTTP request, then we can do that using promises or async-await in JavaScript which was introduced in ES6.

Asynchronous: JavaScript HTTP Request JSON

Asynchronous HTTP requests are more efficient way and user-friendly way.

  1. HTTP GET Request using fetch() method Example code
    
    //uncomment below line if running in node
    //const fetch = require("node-fetch");
    
    fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then(
        response => {
          if (response.ok)
            return response.json();
          else 
            throw new Error("Request Failed");
        },networError => {
          console.log(networError.message);
        })
      .then(jsonResponse => {
        console.log(jsonResponse);
      });
    
    

    If you are trying to run the code in Node.js make sure to install node-fetch. fin the command below-
    npm install node-fetch

  2. HTTP Request using async-await
    
    //uncomment below line if running in node
    //const fetch = require("node-fetch");
    
    const getAPIData= async ()=>{
    
      let url='https://jsonplaceholder.typicode.com/todos/1';
      try{
    
        const response= await fetch(url);
    
        if(response.ok){
          const jsonResponse= await response.json();
          console.log(jsonResponse);
        }
    
      }catch(err){
        console.log("Name :"+ err.name);
        console.log("Message :"+ err.message);
      }
    };
    
    getAPIData();
    

In conclusion, We hope you were able to learn how to make an HTTP request in javascript and get data in JSON response successfully.

✌️ Like this article? Follow us on Facebook and LinkedIn. You can also subscribe to our weekly Feed