Table of Contents
Installation and basics
Global configuration
Custom instance
Interceptor
Home Web Front-end CSS Tutorial Stay DRY Using axios for API Requests

Stay DRY Using axios for API Requests

Apr 05, 2025 am 09:40 AM

Stay DRY Using axios for API Requests

Any web application that communicates with a backend server cannot do without HTTP requests. The front-end needs data, so it requests data over a network HTTP request (or commonly known as Ajax) and the server returns the answer. Almost every website does this somehow these days.

For large websites, we can expect to see more requests like this. More data, more APIs, and more special cases. As the size of the website grows, it is very important to remain organized. A classic concept is DRY (Don't Repeat Yourself), which refers to the process of abstracting code to prevent duplicates. This is ideal because it usually allows us to write code once, use it in multiple places, and update in a single place, rather than in each instance.

We can also use libraries to help us. For Ajax, axios is a popular choice. You may already be familiar with it, and even use it for standalone POST and GET requests during development.

Installation and basics

It can be installed using npm (or yarn):

 npm install axisos
Copy after login

A standalone POST request using Axios looks like this:

 axios.post('https://axios-app.firebaseio.com/users.json', formData)
  .then(res => console.log(res))
  .catch(error => console.log(error))
Copy after login

Native JavaScript There are also many ways to execute JavaScript code. It is worth noting that fetch(). So why use the library? First of all, fetch's error handling is very strange. From the beginning, using axios will be much easier. If you want to see the comparison, we have an article that covers both methods and another discusses the value of this abstract method.

Another reason to use axios? It gives us more DRY opportunities, so let's take a look.

Global configuration

We can set up a global configuration (for example, in our main.js file) that handles all application requests using the standard configuration , which is set via the default object that comes with axios.

This object contains:

  • baseURL: The relative URL used as the prefix of all requests, and each request can be attached to the URL.
  • headers: Custom headers that can be set according to requests
  • timeout: The point in time when the request is aborted, usually in milliseconds. The default value is 0, which means it is not applicable.
  • withCredentials: Indicates whether credentials should be used for cross-site access control requests. Default is false.
  • responseType: Indicates the data type that the server will return. The options include json (default), arraybuffer, document, text, and stream.
  • responseEncoding: Indicates the encoding used to decode the response. The default value is utf8.
  • xsrfCookieName: The name of the cookie used as the XSRF token value, the default value is XSRF-TOKEN.
  • xsrfHeaderName: The name of the HTTP header that hosts the XSRF token value. The default value is X-XSRF-TOKEN.
  • maxContentLength: Defines the maximum size (in bytes) of the allowed HTTP response content
  • maxBodyLength: Defines the maximum size (in bytes) of the allowed HTTP request content

Most of the time, you will only use baseURL, header, and probably timeout. The rest are less commonly used because they have smart defaults, but it's nice to know their existence if you need to fix the request.

This is what DRY does. For each request, we do not have to repeat the baseURL of the API or repeat the important headers we may need in each request.

Here is an example where our API has a base address, but it also has multiple different endpoints. First, we set some default values:

 // main.js
import axios from 'axios';

axios.defaults.baseURL = 'https://axios-app.firebaseio.com' // URL prefix axios.defaults.headers.get['Accept'] = 'application/json' // Default headers for all GET requests axios.defaults.headers.post['Accept'] = 'application/json' // Default headers for all POST requests // Then, in a component, we can use axios more concisely, without setting these headers, but still have the opportunity to customize the final URL endpoint:

// form.js component import axios from 'axios';

export default {
  methods: {
    onSubmit() {
      // URL is now https://axios-app.firebaseio.com/users.json
      axios.post('/users.json', formData)
        .then(res => console.log(res))
        .catch(error => console.log(error))
    }
  }
}
Copy after login

Note: This example is in Vue, but this concept extends to any JavaScript environment.

Custom instance

Setting up Custom Instances is similar to global configuration, but with scopes limited to specified components. So it is still a DRY technology, but with a hierarchy.

We will set up our custom instance in a new file (let's name it authAxios.js) and import it into the "Follow" component.

 // authAxios.js
import axios from 'axios'

const customInstance = axis.create({
  baseURL: 'https://axios-app.firebaseio.com'
})
customInstance.defaults.headers.post['Accept'] = 'application/json'

// Or like this...
const customInstance = axis.create({
  baseURL: 'https://axios-app.firebaseio.com',
  headers: {'Accept': 'application/json'}
})
Copy after login

Then we import this file into the form component:

 // form.js component // import import axios from './authAxios'

export default {
  methods: {
    onSubmit() {
      axios.post('/users.json', formData)
        .then(res => console.log(res))
        .catch(error => console.log(error))
    }
  }
}
Copy after login

Interceptor

An interceptor can handle situations where global configurations or custom instances may be too general, meaning that if you set headers in their objects, it will be applied to the headers for each request in the affected component. The interceptor is able to dynamically change any object properties. For example, we can send different headers based on any condition we choose in the interceptor (even if we set the header in the object).

Interceptors can be in the main.js file or in the custom instance file. The request is intercepted after being sent and allows us to change the handling of the response.

 // Add a request interceptor axios.interceptors.request.use(function (config) {
  // Do something before sending the request, for example, we insert a timeout only for requests with a specific baseURL (config.baseURL === 'https://axios-app.firebaseio.com/users.json') {
    config.timeout = 4000
  } else {
    return config
  }
  console.log(config)
  return config;
}, function (error) {
  // Perform some operations on request errors return Promise.reject(error);
});

// Add a response interceptor axios.interceptors.response.use(function (response) {
  // Perform certain actions on response data, such as console.log, changing header, or adding conditional behavior as we do here, changing routes based on response status or popping up alert box if (response.status === 200 || response.status === 201) {
    router.replace('homepage')
  } else {
    alert('Exception behavior')
  }
  console.log(response)
  return response;
}, function (error) {
  // Perform some operations on response errors return Promise.reject(error);
});
Copy after login

Interceptors, as the name implies, intercept requests and responses to take different actions based on any conditions provided. For example, in the request interceptor above, we only insert the condition timeout when the request has a specific baseURL. For the response, we can intercept it and modify what we return, such as changing the route or showing an alert box, depending on the status code. We can even provide multiple conditions based on different error codes.

As the project scales up, you start to have many routes and nested routes, all of which communicate with the server based on different triggers, and interceptors will be very useful. In addition to the conditions I set above, there are many other situations that may require the use of an interceptor, depending on your project.

Interestingly, we can pop up the interceptor to prevent it from having any impact. We have to assign the interceptor to a variable and pop it out using a properly named pop-up method.

 const reqInterceptor = axios.interceptors.request.use(function (config) {
  // Do something before sending the request, for example, we insert a timeout only for requests with a specific baseURL (config.baseURL === 'https://axios-app.firebaseio.com/users.json') {
    config.timeout = 4000
  } else {
    return config
  }
  console.log(config)
  return config;
}, function (error) {
  // Perform some operations on request errors return Promise.reject(error);
});

// Add response interceptor const resInterceptor = axios.interceptors.response.use(function (response) {
  // Perform certain actions on response data, such as console.log, changing header, or adding conditional behavior as we do here, changing routes based on response status or popping up alert box if (response.status === 200 || response.status === 201) {
    router.replace('homepage')
  } else {
    alert('Exception behavior')
  }
  console.log(response)
  return response;
}, function (error) {
  // Perform some operations on response errors return Promise.reject(error);
});

axios.interceptors.request.eject(reqInterceptor);
axios.interceptors.request.eject(resInterceptor);
Copy after login

Although not very commonly used, you can put the interceptor into a conditional statement or delete it based on certain events.

Hopefully this gives you a good understanding of how axios works and how to use it in your application to keep API requests DRY principles. While we touch the surface by listing common use cases and configurations, axios has many other advantages that you can explore in the documentation, including the ability to cancel requests and prevent cross-site request forgery, as well as other amazing possibilities.

The above is the detailed content of Stay DRY Using axios for API Requests. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Stacked Cards with Sticky Positioning and a Dash of Sass Stacked Cards with Sticky Positioning and a Dash of Sass Apr 03, 2025 am 10:30 AM

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

Google Fonts   Variable Fonts Google Fonts Variable Fonts Apr 09, 2025 am 10:42 AM

I see Google Fonts rolled out a new design (Tweet). Compared to the last big redesign, this feels much more iterative. I can barely tell the difference

How to Create an Animated Countdown Timer With HTML, CSS and JavaScript How to Create an Animated Countdown Timer With HTML, CSS and JavaScript Apr 11, 2025 am 11:29 AM

Have you ever needed a countdown timer on a project? For something like that, it might be natural to reach for a plugin, but it’s actually a lot more

Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Apr 05, 2025 pm 05:51 PM

Questions about purple slash areas in Flex layouts When using Flex layouts, you may encounter some confusing phenomena, such as in the developer tools (d...

How to select a child element with the first class name item through CSS? How to select a child element with the first class name item through CSS? Apr 05, 2025 pm 11:24 PM

When the number of elements is not fixed, how to select the first child element of the specified class name through CSS. When processing HTML structure, you often encounter different elements...

HTML Data Attributes Guide HTML Data Attributes Guide Apr 11, 2025 am 11:50 AM

Everything you ever wanted to know about data attributes in HTML, CSS, and JavaScript.

A Proof of Concept for Making Sass Faster A Proof of Concept for Making Sass Faster Apr 16, 2025 am 10:38 AM

At the start of a new project, Sass compilation happens in the blink of an eye. This feels great, especially when it’s paired with Browsersync, which reloads

See all articles