DEV Community

Cover image for Beginner's Introduction to Axios
Linda
Linda

Posted on

Beginner's Introduction to Axios

Making HTTP requests to fetch/save data is a common task for any client-side JavaScript application. Axios is a JavaScript library that's used to perform HTTP requests. It works in both Browser and Node.js platforms.

It supports all modern browsers, including support for IE8 and higher.

Adding Axios to your project

You can add Axios to your project using any of the methods listed below.

Using npm:

$ npm install axios
Enter fullscreen mode Exit fullscreen mode

Using bower:

$ bower install axios
Enter fullscreen mode Exit fullscreen mode

Using yarn:

$ yarn add axios
Enter fullscreen mode Exit fullscreen mode

Using jsDelivr CDN:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

Using unpkg CDN:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

Making a "GET" request

Let's query the DummyAPI to retrieve a list of users, using axios.get().

import axios from 'axios';

const response = axios.get('https://dummyapi.io/data/api/user?limit=10')
const users = response.data
Enter fullscreen mode Exit fullscreen mode

Since Axios always returns the query in an object data, we can rewrite the code above as using destructuring

import axios from 'axios';

const {data} = axios.get('https://dummyapi.io/data/api/user?limit=10')
const users = data;

Enter fullscreen mode Exit fullscreen mode

Making a "POST" request

A POST request is used to add new data on the Backend. A POST request is similar to a GET request, but instead of axios.get, you use axios.post.

A POST Request also accepts a second argument which is an Object containing the data that is to be added.

Let's add a new user below.

import axios from 'axios';

let newUser = {
    name: 'John',
    email: 'john@gmail.com'
    Gender: Male,
}

addUser (user) => {
    axios.post('https://dummyapi.io/data/api/user/', user)
}

addUser(newUser);
Enter fullscreen mode Exit fullscreen mode

This is a quick introduction for beginners. Axios enables you to do so much more. You can read about more advanced Axios methods in this Article by Faraz Kelhini

Top comments (1)

Collapse
 
rconr007 profile image
rconr007

Thanks for the introduction, very informative.