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

Example of pre-rendering method for Vue single page application

Table of contents Preface vue-cli 2.0 version vue...

JavaScript to achieve a simple countdown effect

This article example shares the specific code of ...

React encapsulates the global bullet box method

This article example shares the specific code of ...

New usage of watch and watchEffect in Vue 3

Table of contents 1. New usage of watch 1.1. Watc...

Solution for VMware Workstation Pro not running on Windows

After the National Day holiday, did any of you fi...

Let's learn about JavaScript object-oriented

Table of contents JavaScript prototype chain Obje...

Basic HTML directory problem (difference between relative path and absolute path)

Relative path - a directory path established based...

js implements mouse in and out card switching content

This article shares the specific code of js to re...

JavaScript to achieve elastic navigation effect

This article shares the specific code for JavaScr...

Server concurrency estimation formula and calculation method

Recently, I need to stress test the server again....