JavaScript: using axios in the browser to make API requests

JavaScript: using axios in the browser to make API requests

axios is a very useful JavaScript library that simplifies the interaction with remote APIs.

axios is a very useful JavaScript library that simplifies the interaction with remote APIs.

axios makes use of the Promise API to handle requests so it's 100% compatible with the async/await model. This library can be either used with Node.js or in a web browser. In this article we're going to see how to use it on the client side.

Before using axios in the client, however, make sure that the remote APIs support CORS requests.

First, we need to define the API's remote base URL:


'use strict';

const API_URL = 'https://jsonplaceholder.typicode.com/';


Then we can create a function that defines the specific endpoint to use and returns a Promise.


const getAPIData = query => {

    const {id, endpoint} = query;
    const url =  API_URL + endpoint + '/' + id

    return axios.get(url);
};

At this point we also need to handle the incoming data and parse it.


const parseData = data => {
    const {title, body} = data;
    const post = document.createElement('article');

    post.innerHTML = `<h2>${title}</h2><p>${body}</p>`;

    document.body.appendChild(post);
};

Since Promises can be rejected due to an error with our request, we have to handle this special case.


const handleError = error => {
    const pre = document.createElement('pre');
    pre.innerHTML = JSON.stringify(error, null, 2);
    document.body.appendChild(pre);
};

Finally, we put all together by using the async/await model.


const init = async () => {
    try {
        const response = await getAPIData({id: 2, endpoint: 'posts'});
        parseData(response.data);
    } catch(err) {
        handleError(err);
    }
};

Note that in axios the data returned by the remote request are contained in the data property.

You can see the above code in action on the following page.