Beginner's Introduction to Axios

Javascript

Javascript

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


Using bower:

$ bower install axios


Using yarn:

$ yarn add axios


Using jsDelivr CDN:

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


Using unpkg CDN:

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



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


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;



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);



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

Continue Reading

Continue Reading

Continue Reading

Continue Reading