Axios crash course in Cules Coding by @thatanjan

Axios crash course

In this blog, you will learn how to use Axios to make HTTP requests in JavaScript.

What is Axios?

Axios is a library that makes it easy to make HTTP requests in JavaScript. It is promise based. It is much more browser compatible than fetch API because it uses XMLHttpRequest behind the scenes. You can also use Axios in Node.js.

https://github.com/axios/axios

How to use Axios?

You can install Axios using npm or yarn.

1npm install axios
2# or
3yarn add axios

or you can use CDN.

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

We will use ReqRes API for testing. It gives you fake data to test your code.

How to make a GET request?

We will fetch some users from ReqRes API.

1const url = 'https://reqres.in/api'
2const getUsers = async () => {
3 const result = await axios.get(`${url}/users/`)
4
5 console.log(result)
6}
7
8getUsers()

Explanation:

  • You will get a response object. The response is already parsed as JSON.
  • It has a data property. The data property is holding the data.

Pass query parameter

1const url = 'https://reqres.in/api'
2const getUsers = async () => {
3 const result = await axios.get(`${url}/users/`, {
4 params: {
5 per_page: 10,
6 },
7 })
8
9 // or
10 // const result = await axios.get(`${url}/users?per_page=10`)
11
12 console.log(result)
13}
14
15getUsers()

How to make a POST request?

We will send a POST request to ReqRes API to create a new user. It will not create a new user. It will only mimic the process and return us a response.

1const url = 'https://reqres.in/api'
2
3const createUser = async () => {
4 const result = await axios.post(`${url}/users`, {
5 name: 'Anjan',
6 job: 'Developer',
7 })
8 console.log(result)
9}

Explanation:

  • You can pass a request body as a second parameter which will contain data about the user.
  • You will get a response object. The response is already parsed as JSON.

Config object

You can pass a config object to axios. Learn more from the docs .

Request headers

Let's see how we can pass a request header. We are passing an Authorization header which normally holds the user's token.

1const url = 'https://reqres.in/api'
2
3const createUser = async () => {
4 const config = {
5 headers: {
6 Authorization: 'token',
7 },
8 }
9
10 const result = await axios.post(
11 `${url}/users`,
12 {
13 name: 'Anjan',
14 job: 'Developer',
15 },
16 config
17 )
18
19 console.log(result)
20}
21
22createUser()

Axios instance

Our URL was always the same and we are passing it manually to every request. But we can create an instance of Axios which will have the URL from the start. and use it to make requests. You can also store other configs like request headers.

1const url = 'https://reqres.in/api'
2
3const instance = axios.create({
4 baseURL: url,
5 headers: {
6 Authorization: 'token',
7 },
8})
9
10const getUsers = async () => {
11 const result = await instance.get(`/users`, {
12 params: {
13 per_page: 10,
14 },
15 })
16 console.log(result)
17}

Now we can use the instance to make requests. We are just only passing the endpoints not the whole URL.

Axios transform the response

You can transform the response data using the transformResponse property in config.

1const createUser = async () => {
2 const config = {
3 headers: {
4 Authorization: 'dfdkfj',
5 },
6
7 transformResponse: axios.defaults.transformResponse.concat(data => {
8 data.modified = 'modified'
9
10 return data
11 }),
12 }
13
14 const result = await axios.post(
15 `${url}/users`,
16 {
17 name: 'Anjan',
18 job: 'Developer',
19 },
20 config
21 )
22 console.log(result)
23}

Explanation:

  • transformResponse takes an array of functions that will be called on the response data one after another.
  • It will override the default transformResponse functions. I don't recommend that. Instead, we can extend the default transformResponse with our functions.
  • We are using the concat method of the array to add our functions.

Shameless Plug

I have made an Xbox landing page clone with React and Styled components. I hope you will enjoy it. Please consider like this video and subscribe to my channel.

That's it for this blog. I have tried to explain things simply. If you get stuck, you can ask me questions.

Contacts

Blogs you might want to read:

Videos might you might want to watch:

Next PostNPM crash course