Simple encapsulation of axios and example code for use

Simple encapsulation of axios and example code for use

Preface

Recently, when I was building a project, I thought about the encapsulation of requests, and then I thought about how to encapsulate it. Although it may be a small thing for you big guys, it is also a small challenge for me. In my imagination, some basic configurations and specific interfaces requested should be placed in two files, so I created two new files axios.js and api.js

axios.js

axios.js is mainly for some basic configuration of axios: baseURL request interceptor response interceptor etc.

import axios from 'axios';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import router from '../router';

First, introduce axios into the current js. The purpose of introducing element is to use its components in the current js, and the purpose is to directly prompt various return values ​​in the response interceptor. The router is introduced to redirect pages according to the specific return value in the response interceptor. For example, if there is no permission, it will jump to the login page.

if (process.env.NODE_ENV === 'development') {
  axios.defaults.baseURL = 'api';
} else if (process.env.NODE_ENV === 'production') {
  axios.defaults.baseURL = 'https://xxxxxxxxxx/index/';
}

For baseURL processing, I distinguish between development environment and production environment

//The request interceptor distinguishes the request headers when sending normal requests and when sending formdata axios.interceptors.request.use((config) => {
  config.headers['Content-Type'] = 'application/json';
  if (config.method === 'post') {
    //Request header for FormData if (Object.prototype.toString.call(config.data) === '[object FormData]') {
      // Request interceptor processing config.headers['Content-Type'] = 'multipart/form-data';
    } else if (Object.prototype.toString.call(config.data) === '[object String]') {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    }
  } else {
    config.headers['Content-Type'] = 'application/json';
  }
  return config;
});

//Response interceptor axios.interceptors.response.use(
  (config) => {
    let value = config.data;
    if (config.status && config.status === 200) {
      if (typeof value === 'string') {
        if (value === 'timeout') {
          ElementUI.MessageBox.confirm('You have not operated for too long or you do not have permission to operate. Please go to the login page and log in again?', 'Prompt', {
            confirmButtonText: 'Confirm',
            type: 'warning'
          }).then(() => {
            router.push({ name: 'login' });
          });
        }else {
          ElementUI.Message.info(value);
        }
      }
    }
    return config;
  },
  (err) => {
    let value = err.response.statusText;
    switch (err.response.status) {
      case 400:
        ElementUI.Message.error('The syntax format is incorrect and the server cannot understand this request')
        break;
      case 401:
      case 403:
      case 404:
      case 405:
        ElementUI.Message.warning(value);
        break;
      default:
        ElementUI.Message.error('An error occurred during the operation. This operation is invalid!' + value);
        break;
    }
    return err.response
  }
);

For the response interceptor, I process it according to the value returned by my backend. Since I have not done much work with the backend, I just simply process the return.

The following is a package of get and post

export async function axiosGet(url, params = {}) {
  let res = await axios.get(url, { params: params });
  if(res.status === 200){
    return res.data
  }else {
    throw res.statusText
  }
}

export async function axiosPost(url, params = {}) {
  let res = await axios.post(url, params);
  if(res.status === 200){
    return res.data
  }else {
    throw res.statusText
  }
}

Use async and await to directly get the return value for judgment. If the return is successful, the return value is output. If not, an error is thrown.

Finally, export the encapsulated method

api.js

The entire api.js is where all interfaces in the project are stored

import { axiosGet, axiosPost } from './axios'

Introduce axios.js and obtain the encapsulated axiosGet and axiosPost

export default {
  getLogin:(params = {}) => {
    return axiosPost('/login', params)
  },
  getUser:(params = {}) => {
    return axiosGet('http://localhost:3000/user', params)
  }
}

Here I use two simple interfaces as examples, and the processing in api.js has been completed

Use the configured interface

At this point our axios has been packaged, and the next step is to demonstrate its use

import DbauditServer from '@/server/api'
//Introduce api.js in the file to call the interface

let formData = new FormData
formData.append('password', this.formLabelAlign.password)
let res1 = await DbauditServer.getLogin(formData) //Just call it and it will work normally let res2 = await DbauditServer.getUser()

Of course, it can be more detailed. Because when encapsulating get and post before, the error return value is thrown directly. Therefore, the call of the interface can also be wrapped with try catch to perform specific processing on the error.

Summarize

This is the end of this article about the simple encapsulation and use of axios. For more related axios simple encapsulation content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of Axios encapsulation and API interface management in Vue
  • Detailed explanation of Vue 2.0 encapsulation axios notes
  • Example code using axios and encapsulation in vue
  • Axios encapsulation method for handling various abnormal situations in requests
  • Axios encapsulation, using interceptors to uniformly process interfaces, super detailed tutorial (recommended)
  • Solve the error prompt problem of encapsulated request status of vue axios
  • Detailed explanation of the encapsulation of axios requests in vue
  • How to use Axios to encapsulate http requests in Vue projects
  • An example of secondary encapsulation of axios in vue
  • Use async await to encapsulate axios method

<<:  Analysis of mysql view functions and usage examples

>>:  How to solve the problem of -bash: /usr/bin/yum: No such file or directory after typing yum in linux

Recommend

Sample code for CSS dynamic loading bar effect

Using the knowledge of CSS variables, I will dire...

Analysis of the method of setting up scheduled tasks in mysql

This article uses an example to describe how to s...

Project practice of deploying Docker containers using Portainer

Table of contents 1. Background 2. Operation step...

How to compile and install xdebug in Ubuntu environment

This article describes how to compile and install...

HTML introductory tutorial HTML tag symbols quickly mastered

Side note <br />If you know nothing about HT...

mysql 8.0.16 winx64.zip installation and configuration method graphic tutorial

This article shares the specific code of MySQL 8....

Simple steps to configure Nginx reverse proxy with SSL

Preface A reverse proxy is a server that receives...

How to install MySQL under Linux (yum and source code compilation)

Here are two ways to install MySQL under Linux: y...

Meta declaration annotation steps

Meta declaration annotation steps: 1. Sort out all...

Steps of an excellent registration process

For a website, it is the most basic function. So l...

Detailed explanation of grep and egrep commands in Linux

rep / egrep Syntax: grep [-cinvABC] 'word'...

centos 7 modify sshd | prohibit root login and sshd port script definition

1. Create a new user wwweee000 [root@localhost ~]...

CSS3 analysis of the steps for making Douyin LOGO

"Tik Tok" is also very popular and is s...

Solution to the problem that Java cannot connect to MySQL 8.0

This article shares a collection of Java problems...