What is 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.
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'));
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}
.
Learn more:
- Recommended tutorial: Learn how to make Axios requests
- Documentation
Was this article helpful?