Uses of Axios

Axios is a promised-based HTTP client for JavaScript. It has the ability to make HTTP requests from the browser and handle the transformation of request and response data. Axios is a lightweight HTTP client based on the XMLHttp requests service. It is similar to the Fetch API and is used to perform HTTP requests.

Axios is a very popular promise-based HTTP client. It can help you to efficiently connect your web application with APIs. It has a pretty straightforward syntax and very extensive documentation. Let’s have a look at how to use it in React apps.

The code snippet below shows an example usage of an Axios get request, taken from the LMS sharp example project: 

clientside/src/Models/Entities/User.tsx.

import axios from ‘axios’;

// Some lines have been removed here

function getGroups() {

    return axios.get(`${SERVER_URL}/api/account/groups`)

        .then(({ data }) => {

            return data.map((groupName: any) => { return { display: groupName, value: groupName }});

        });

}

In the get request above, the argument passed through is the URL.  An optional second argument can be passed with parameters.

An example of an Axios   post request is shown in the code snippet below, taken from the LMS sharp example project: 

clientside/src/Views/Components/CRUD/UserList.tsx.

protected resetPassword = (entity: IUser) => axios

        .post(`${SERVER_URL}/api/account/reset-password-request`, {Username: entity.email})

        .then(data => this.onResetPasswordSuccess(entity))

        .catch(data => alert(`${data}`, ‘error’));

Copy

The post method is similar to the get method. In the post request above, the second argument is an object containing the post parameters, i.e. {username: entity.email}.

Leave a Reply

Your email address will not be published. Required fields are marked *

Proudly powered by WordPress | Theme: Orton Blog by Crimson Themes.