Axios http request tutorial

axios http request tutorial eyecatch

Axios is a popular JavaScript library used to make HTTP requests from the browser (client side) and Node.js (server side). It simplifies the process of interacting with APIs and handling HTTP requests and responses. Axios supports a wide range of features that make it a powerful and flexible tool for making HTTP requests.

Features

Promise-based: Axios uses Promises to handle asynchronous operations, making it easier to work with async/await syntax.
Interceptors: Allows you to modify requests or responses before they are handled by “then” or “catch”.
Automatic request body serialization: Axios can transform request body to JSON (application/json), Multipart / form data (multipart/form-data) and URL encoded form (application/x-www-form-urlencoded).
Cancel requests: Allows you to cancel requests using the CancelToken.
Client-side support for protecting against XSRF: Axios supports Cross-Site Request Forgery (XSRF) protection.

Installing

Axios can be installed by using node.js package managers like npm or yarn.
Command (bash or cmd):

​​npm install -S axios

or

yarn add axios

Basic usage

Making request

GET

import axios from "axios";
axios.get("/api/v1/products", {
  headers: {
    "Authorization": "mykey123"
  },
  params: {
    page: 1,
    limit: 20
  },
}).then((response) => {
  console.log(response);
}).catch((error) => {
  console.log(error);
}).finally(() => {
  //clean up...
});

Parameters:
-First: Target URL.
-Second: Configuration for this request. In the example above, I set an authorization header and 2 query params.
Handle response:
-then(): This callback will be executed when the server (endpoint) returns a response with status code 2xx.
-catch(): This callback will be executed when the server has a problem and can not fulfill our request. Status codes are 4xx or 5xx. 
-finally(): This callback will be executed after finishing the request (after then() and catch()).

POST

It is similar to GET but we normally set the data for this request. For example creating a product.

axios.post("/api/v1/products", {
  name: "Ice cream",
  price: 10
}, {
  headers: {
    "Authorization": "mykey123"
  },
})

Parameters:
-First: Target URL.
-Second: Data to be posted.
-Third: Configuration for this request.
Handle response: Same as GET request.
There are other methods: put(), delete(), patch(), etc… and their usage is similar to get() and post(). Request method depends on your API configuration.
Alternatively, you can make all kinds of requests using only one constructor. This is convenient for someone who doesn’t want to remember the parameter index of each method.

axios({
  method: "GET",
  url: "/api/v1/products",
  headers: {
    "Authorization": "mykey123"
  },
  params: {
    page: 1,
    limit: 20
  },
}).then((response) => {
  console.log(response);
});

Interceptor

Interceptors allow you to run your code or modify the request or response before they are handled by then() or catch(). I personally use it to add authorization key to requests. The setup is also simple.

const axiosInstance = axios.create();
axiosInstance.interceptors.request.use(function (config) {
  //Add custom token
  config.headers.Authorization = "mytoken123";
  return config;
});

axiosInstance.interceptors.response.use(
  function (response) {
    //Handle response
    return response;
  },
  function (error) {
    //Handler error
    if (
      error.response.status === 401
    ) {
      //Redirect to login page
      window.location.pathname = "/login";
    }
    return Promise.reject(error);
  },
);

Now you can use axiosInstance to make requests normally. You can set the interceptor directly to the global Axios instance using axios.interceptors.request.use() but it is not recommended.

Cancellation

This is useful when you want to cancel a request when it takes too much time.

axios.get("/api/v1/products", {
signal: AbortSignal.timeout(5000) //Aborts request after 5 seconds
}).then((response) => {
//…
});

Handling multiple requests

Bad practice:
Don’t call many requests one by one. It only slows your application down.

const productResponse = await axios.get("/api/v1/products");
const giftResponse = await axios.get("/api/v1/gifts");//wait for product request to complete before calling gift request

When combined with Promise you can handle many requests at once. Depending on the purpose you can group your http requests in different ways.

Promise.all()

This method will execute all requests at once. If all requests are successful or one request is failed, it will go to then() or catch() block.

Promise.all([axios.get("/api/v1/products"), axios.get("/api/v1/gifts")]).then((values) => {
  console.log(values[0]);//product response
  console.log(values[1]);//gift response
}).then((error) => {
  console.log(error);//first error
});

Promise.allSettled()

This method will execute all requests at once the same as Promise.all() , but the difference is that we will get both success and failed responses in then().

Promise.allSettled([axios.get("/api/v1/products"), axios.get("/api/v1/gifts")]).then((results) => {
  //check product response
  if (results[0].status === "fulfilled") {
    //success response
  }
  if (results[0].status === "rejected") {
    //failed response
  }
});

There are other promise methods like Promise.any(), Promise.race(), … that allow you to execute many requests at the same time. They have different ways to handle response and error. You will need to choose the correct one to use.

Summary

Axios is a powerful and flexible library for making HTTP requests. Its support for Promises makes it easy to use with modern JavaScript features like async/await. With additional features like interceptors, request cancellation, and error handling. Axios is a great choice for any project that needs to interact with APIs.

Reference:
Getting Started | Axios Docs (axios-http.com)
Promise – JavaScript | MDN (mozilla.org)

関連記事

カテゴリー:

ブログ

情シス求人

  1. 登録されている記事はございません。
ページ上部へ戻る