axios

Axios is a promise-based HTTP client for web browsers and Node.js, providing an easy-to-use library to make REST API calls.

Features

  1. Promise-based: Axios returns JavaScript promises for all operations, allowing asynchronous handling and enabling call chaining using .then(), .catch(), or async/await syntax.

  2. Error Handling: Axios provides a powerful set of tools for handling request errors, offering more context information and giving you greater control over handling failure scenarios.

  3. JSON Data Transformation: Axios automatically converts JSON data, eliminating the need for explicit parsing of responses. This simplifies API data handling, reducing boilerplate code.


Installation

To install Axios, you can use the npm (npm install) or yarn (yarn add) command in a Node.js environment to install the 'axios' package.

Installation

npm install axios

Usage

Axios is a promise-based HTTP client that can be used in both browsers and Node.js environments.

  • Name
    Use Methods
    Type
    Usage
    Description

    It provides methods such as axios.get(), axios.post(), axios.put(), axios.delete() for sending HTTP requests.

Cautions

  • Name
    Error Handling
    Type
    Cautions
    Description

    By default, Axios does not reject promises for HTTP error status codes (400 and above). To handle this, you can use the validateStatus configuration option or manually check the response status code to handle errors.

  • Name
    Request Cancellation
    Type
    Cautions
    Description

    Axios provides the ability to cancel HTTP requests, which can be useful for preventing duplicate executions of requests or aborting unnecessary requests.

  • Name
    Security
    Type
    Cautions
    Description

    When including sensitive information such as API keys or authentication tokens, it is important to ensure that this information is not exposed. It is recommended to use environment variables or separate security modules to handle such sensitive information.

Usage

import axios from 'axios';

// GET 요청
axios.get('https://api.example.com/data')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error', error);
});

// POST 요청
axios.post('https://api.example.com/data', {
  title: 'Hello',
  description: 'World'
})
.then(response => {
  console.log(response.data);
})
.catch(error => {
  console.error('Error', error);
});

Customization

Axios can be a powerful and highly customizable HTTP client.

Explanation

  • Name
    Global Axios Defaults
    Type
    Customization
    Description

    You can set global Axios default configurations to apply default values to all requests. For example, you can set a baseURL to use the same default URL for all requests, like this:

  • Name
    Custom Headers
    Type
    Customization
    Description

    You can set custom headers for specific requests or for all requests. For example, if you want to add a specific API key to all requests, you can do it like this:

  • Name
    Error Handling
    Type
    Customization
    Description

    You can customize how errors are handled for requests or responses. For example, if you want to add common handling for specific HTTP error codes, you can do it like this:

Customization

// Global Axios Defaults
axios.defaults.baseURL = 'https://api.example.com';

// Custom Headers
axios.defaults.headers.common['Authorization'] = `Bearer ${API_KEY}`;

// Error Handling
axios.interceptors.response.use(
  response => response,
  error => {
    if (error.response.status === 401) {
      console.log('unauthorized, logging out ...');
    }
    return Promise.reject(error);
  }
);

Example

We are utilizing Axios for performing SSR (Server-Side Rendering) using the getServerSideProps.

Additional Explanation

  • Name
    const apiUrl = process.env.NEXT_PUBLIC_API_URL
    Type
    Example
    Description

    We are retrieving the environment variable NEXT_PUBLIC_API_URL and storing it in the apiUrl variable. This environment variable can be configured differently depending on the .env file or the deployment environment.

  • Name
    const res = await axios.get(...)
    Type
    Example
    Description

    We are using the axios library to send an HTTP GET request. The URL is constructed by combining the apiUrl we previously set and the name parameter. This request is handled asynchronously, and the execution is paused until the response arrives.

  • Name
    const character = res.data.data
    Type
    Example
    Description

    Axios automatically converts the response into a JavaScript object. The data property of this object contains the data sent from the server.

  • Name
    catch (error) { ... }
    Type
    Example
    Description

    Any errors that occur in the above code will be caught in this catch block. In case of an error, we log the error to the console and return the notFound object to display the 404 page.

[name].jsx

export async function getServerSideProps(context) {
  const { name } = context.params
  const apiUrl = process.env.NEXT_PUBLIC_API_URL

  try {
    const res = await axios.get(
      `${apiUrl}/api/lostark/searchCharacter?name=${name}`,
    )
    const character = res.data.data

    if (!character) {
      throw new Error('Failed to fetch character data')
    }

    return {
      props: {
        character,
      },
    }
  } catch (error) {
    console.error(error)
    return {
      notFound: true,
    }
  }
}