Server requests in JavaScript-based application is a common task. Different libraries try to provide an easy way to solve this problem.

Below are examples to show how to send simple HTTP GET requests using Fetch API, jQuery, and Axios. One example shows the request from React to a backend using Fetch API and useEffect hook. 

To make an API requests examples use free fake API - {JSON} Placeholder. JSONPlaceholder is exposing multiple endpoints which can be used for sending GET or POST requests to.

Using Fetch API to make a GET request to a third party API service

The Fetch API is basically a modern replacement for XHR. It was introduced to make asynchronous HTTP requests easier to do in JavaScript. The Fetch API is built into most modern browsers, and it enables to perform server requests without the necessity of using third-party libraries. It is a promised-based API.

The basic structure of GET requests using Fetch API

// Simple GET request using fetch
// replace ./api.data.json with your JSON feed fetch('./api.data.json') .then((response) => { return response.json() }) .then((data) => { console.log(data) // work with data (JSON format) }) .catch((err) => { // work with an error here })

 Key points to remember:

  • The first parameter of the Fetch function - the URL (the path to the resource we want to fetch).
  • The response object contains information about the response object itself. It includes headers, status codes, etc. Call the response.json() function to get JSON data from the response object.
  • Fetch API does not throw an error if the request returns a 400 or 500 status code. It is marked as a successful response and passed to the ‘then’ function. Only a network error or a request not completing will throw an error. Write custom logic using ‘response.status’ to throw an error.

404 Not Found - The server has not found anything matching the Request-URI.

500 Internal Server Error - The server encountered an unexpected condition which prevented it from fulfilling the request.

 A working example of using Fetch API in an HTML page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fetch Api</title>
</head>
<body>
    <div>
        <h1>Getting Started With Fetch API</h1>
        <button id="fetchUserDataFetchAPI">Fetch User Data with Fetch API</button>
    </div>
    <hr>
    <div id="fetchApiResponse"></div>
    <script>
        // The Fetch API 
        document.getElementById('fetchUserDataFetchAPI').addEventListener('click', fetchUserData);
        function fetchUserData() {
            fetch('https://jsonplaceholder.typicode.com/users/1')
                .then(response => {
                    if (!response.ok) {
                        const message = `An error has occured: ${response.status}`;
                        throw new Error(message);
                    }
                    return response.json();
                })
                .then(user => {
                    // console.log(user);
                    let output = '<h2>User - ' + user.name + '</h2>';
                    output += `<li> Username - ${user.username}</li>`;
                    output += `<li> Website - ${user.website}</li><hr>`;
                    document.getElementById("fetchApiResponse").innerHTML = output;
                })
                .catch(error => {
                    let output = `An error - ${error.message} <hr>`; // 'An error has occurred: 404'
                    document.getElementById("fetchApiResponse").innerHTML = output;
                })
        }
    </script>
</body>
</html>
  1. Save the example in a file with an HTML extension.
  2. Open in a browser.
  3. Clicking the button will retrieve the data.

JavaScript code inside script tags adds a click event listener function to the fetchUserDataFetchAPI.

The fetchUserData function contains the code which is needed to retrieve data from endpoint in JSON format.

The endpoint is passed into the fetch function as string. The fetch returns a promise.

The first call of then checks errors with 400 or 500 status codes and extracts the JSON part of the response object.

The second call of then is used to output the JSON result to the console and to work with data.

Using jQuery to make a GET request

jQuery is a fast and feature-rich JavaScript library. It makes event handling, animation, and Ajax much simpler with an API that works across different browsers.

There are two ways to retrieve a JSON feed with jQuery:

  1. using the getJSON() function;
  2. access JSON via an AJAX request

You'll need to load the jQuery JavaScript library before using of any of this custom codes.

The basic structure of GET requests using jQuery

// using the getJSON() function.
$(document).ready(function () {
  // replace ./api.data.json with your JSON feed
  $.getJSON('./api.data.json', function (data) { 
    console.log(data) // handle success (JSON format data)
  })
})

 getJSON() function a shorthand Ajax function, which is equivalent to the next example:

// access JSON via an AJAX request
$(document).ready(function () {
  var data
  $.ajax({
    dataType: 'json',
    // replace ./api.data.json with your JSON feed
    url: './api.data.json', 
    data: data,
    // success callback function is passed the returned data
    success: function (data) { 
      console.log(data) // work with data (JSON format)
    },
  })
})

$.ajax() is essentially an object taking values it will use to construct the request.

A working example of using jQuery in an HTML page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Api</title>
</head>
<body>
    <div>
        <h1>Getting Started With Jquery Fetch</h1>
        <button id="fetchUserDataJquery">Fetch User Data with Jquery API</button>
    </div>
    <hr>
    <div id="jqueryApiResponse"></div>
    <script>
        // Jquery Fetch 
        document.getElementById('fetchUserDataJquery').addEventListener('click', fetchUserDataJquery);
        function fetchUserDataJquery() {
            $.getJSON("https://jsonplaceholder.typicode.com/users/2", function (user) {
                console.log("JSON Data: " + user.name);
                let output = '<h2>User - ' + user.name + '</h2>';
                output += `<li> Username - ${user.username}</li>`;
                output += `<li> Website - ${user.website}</li><hr>`;
                document.getElementById("jqueryApiResponse").innerHTML = output;
            })
                .fail(function (jqxhr, textStatus, error) {
                    var err = textStatus + ", " + error;
                    let output = `An error - ${err}`;
                    document.getElementById("jqueryApiResponse").innerHTML = output;
                    console.log("Request Failed: " + err + "<hr>");
                });
        }
    </script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"
        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
</body>
</html>

 Using Axios to make a GET request 

As with Fetch API, Axios is promise-based. It can be used for node.js and the browser. On the server-side it uses the native node.js http module, while on the client (in a browser) it uses XMLHttpRequests.

Axios has the ability to intercept and cancel request, it also has a built-in feature that provides client-side protection against cross-site request forgery.

The main difference Axios from Fetch API is that it already returns the result as JSON object, so we don't need to convert it.

You'll need to load the Axios JavaScript library before using it.

The basic structure of GET requests using Axios

// replace ./api.data.json with your JSON feed
axios.get('./api.data.json') 
  .then(function (response) {
    console.log(response); // handle success
  })
  .catch(function (error) {
    console.log(error); // handle error
  });

A working example of using Axios in an HTML page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Axios Api</title>
</head>
<body>
    <div>
        <h1>Getting Started With Axios API</h1>
        <button id="fetchUserDataAxiosAPI">Fetch User Data with Axios API</button>
    </div>
    <hr>
    <div id="axiosApiResponse"></div>
    <script>
        // Axios Fetch 
        document.getElementById('fetchUserDataAxiosAPI').addEventListener('click', fetchUserDataAxios);
        function fetchUserDataAxios() {
            axios.get('https://jsonplaceholder.typicode.com/users/3')
                .then(function (response) {
                    // handle success
                    console.log(response.data);
                    var user = response.data;
                    let output = '<h2>User - ' + user.name + '</h2>';
                    output += `<li> Username - ${user.username}</li>`;
                    output += `<li> Website - ${user.website}</li><hr>`;
                    document.getElementById("axiosApiResponse").innerHTML = output;
                })
                .catch(error => {
                    let output = `An error - ${error.message} <hr>`; // 'An error has occurred: 404'
                    document.getElementById("axiosApiResponse").innerHTML = output;
                })
        }
    </script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</body>
</html>

 GET request using Fetch API with React useEffect() hook

This example sends the same GET request from React using Fetch API and useEffect() hook from a function component instead of lifecycle methods of a traditional React class component.

The example consists of 2 files:

  1. react.html file;
  2. app.js file

For this example React was added to an existing HTML page (react.html).

react.html file has <div> with a unique id HTML attribute. This allows to find it from the JavaScript code and display a React component inside of it.

Four <script> tags in react.html file are:

  1. React - the React top level API;
  2. React DOM - adds DOM-specific methods;
  3. Babel - a JavaScript compiler to use ES6+ in old browsers;
  4. app.js file - component code that does the fetching.

react.html file

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>Fetching in React</title>
    <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
    <div id="root"></div>
    <div><a href="/../index.html">Back</a></div>
    <script type="text/babel" src="/app.js"></script>
</body>
</html>

app.js file

// GET request using fetch inside useEffect React hook
'use strict';

const UserFetch = () => {
    const [loading, setLoading] = React.useState(true);
    const [error, setError] = React.useState(false)
    const [user, setUser] = React.useState({});

    React.useEffect(() => {
        const fetchData = async () => {
            setLoading(true);
            try {
                let response = await fetch('https://jsonplaceholder.typicode.com/users/5');
                if (!response.ok) {
                    const message = `An error has occured: ${response.status}`;
                    throw new Error(message);
                }
                let user = await response.json();
                setUser(user);
            } catch (error) {
                console.log(error.message);
                setError(true);
            }
            setLoading(false);
        }
        fetchData();
    }, []); // a blank array [] so that this effect only runs once.

    return (
        <div>
            {loading && <div>Loading</div>}
            {!loading && error && <div>Fetch not working. Check the console.</div>}
            {!loading && !error
                && (
                    <div>
                        <h2> User - {user.name}</h2>
                        <li> Username - {user.username}</li>
                        <li> Website - {user.website}</li>
                    </div>
                )}
        </div>
    )
}

class App extends React.Component {
    render() {
        return (
            <div>
                <h1>Fetching Data with React!</h1>
                <UserFetch />
            </div>
        )
    }
}

ReactDOM.render(<App />, document.getElementById('root'))

Setting Up the project

  • Create a new project folder;
  • Inside that folder add a react.html and app.js files.
  • Opening react.html file will load code from the app.js file and fetch the data.

Getting Data on Page Load

useEffect() hook can perform data fetching side-effect in React.

The fetchData function does not run until we actually call it. To fetch the data as soon as our component is loaded use it inside useEffect() hook.

useEffect() hook in app.js file has an empty dependency array because we need the data to be fetched only once.

References and further reading

The entire code for the project is available on this GitHub repo.

Fetch API — Introduction To Promised-based Data Fetching In Plain JavaScript

Fetching data from the server - Client-side_web_APIs/Fetching_data

jQuery.get() https://api.jquery.com/jquery.get/

jQuery.ajax() https://api.jquery.com/jquery.ajax/

Axios - Promise based HTTP client for the browser and node.js

Add React to a Website https://reactjs.org/docs/add-react-to-a-website.html

{JSON} Placeholder - Free fake API for testing and prototyping

How to fetch data with React Hooks

How to Use Fetch with async/await