Close Menu
    Facebook X (Twitter) Instagram
    TecAdmin
    • Home
    • FeedBack
    • Submit Article
    • About Us
    Facebook X (Twitter) Instagram
    TecAdmin
    You are at:Home»General Articles»How to Make an HTTP request in JavaScript

    How to Make an HTTP request in JavaScript

    By RahulFebruary 20, 20232 Mins Read

    `XMLHttpRequest` and `fetch()` are two powerful functions in JavaScript that can be used to make Ajax calls. XMLHttpRequest (XHR) is a legacy technology that’s been around since the early days of the web. It allows you to make HTTP requests from the client side, and it’s still widely used today. The fetch() function, meanwhile, is a newer addition to JavaScript that’s slowly taking over as the preferred way to make Ajax calls. It uses Promises, so it’s easier to write and debug, and it also supports streaming and other modern features.

    Both XMLHttpRequest and fetch() are great tools for making Ajax calls, but fetch() is generally considered the better option for most applications. So if you’re looking for a way to make Ajax calls in JavaScript, give fetch() a try. We think you’ll be pleasantly surprised by the results!

    Make HTTP Request in JavaScript

    Here is an example of using XMLHttpRequest to make a GET request to retrieve data from remote API:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    const xhr = new XMLHttpRequest();
    xhr.responseType = 'json';
     
    xhr.onreadystatechange = () => {
      if (xhr.readyState === XMLHttpRequest.DONE) {
        console.log(xhr.response);
      }
    }
     
    xhr.open('GET', 'https://api.example.com/');
    xhr.setRequestHeader('Authorization', 'Bearer ' + API_KEY);
    xhr.send();

    Here is an example of using fetch() to make a GET request to retrieve data from a remote API.

    1
    2
    3
    4
    5
    6
    7
    fetch('https://api.example.com/', {
      headers: {
        'Authorization': 'Bearer ' + API_KEY
      }
    })
      .then(response => response.json())
      .then(data => console.log(data));

    Both examples assume that you have an API key stored in a variable called API_KEY.

    You can also use fetch() to make other types of HTTP requests, such as POST, PUT, and DELETE, by passing an options object as the second argument. For example:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    fetch('/url', {
      method: 'POST',
      body: JSON.stringify({
        name: 'John',
        age: 30,
      }),
      headers: {
        'Content-Type': 'application/json',
      },
    });

    Note that `XMLHttpRequest` and `fetch()` are asynchronous, which means that the code will not block while the request is being made. Instead, the response will be processed in a callback function or with a promise.

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp

    Related Posts

    How to Change Port in Next.Js

    Ubuntu 24.04 LTS: The Future of Open-Source Excellence

    How to Execute Linux Commands in Python

    Add A Comment

    Leave A Reply Cancel Reply

    Advertisement
    Recent Posts
    • How to Change Port in Next.Js
    • Ubuntu 24.04 LTS: The Future of Open-Source Excellence
    • How to Execute Linux Commands in Python
    • Creating MySQL User with GRANT OPTION
    • Where to find crontab (cron) logs in Ubuntu & Debian
    Facebook X (Twitter) Instagram Pinterest
    © 2023 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.