Several ways to encapsulate axios in Vue

Several ways to encapsulate axios in Vue

Basic Edition

Step 1: Configure Axios

First, create a Service.js, which stores the axios configuration and interceptors, and finally exports an axios object. I usually use elementUI more often, you can also use your own UI library here.

import axios from 'axios'
import { Message, Loading } from 'element-ui'
const ConfigBaseURL = 'https://localhost:3000/' //Default path, you can also use env to determine the environment let loadingInstance = null //Here is loading
//Use the create method to create an axios instance export const Service = axios.create({
  timeout: 7000, // Request timeout baseURL: ConfigBaseURL,
  method: 'post',
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})
// Add request interceptor Service.interceptors.request.use(config => {
  loadingInstance = Loading.service({
    lock: true,
    text: 'loading...'
  })
  return config
})
// Add response interceptor Service.interceptors.response.use(response => {
  loadingInstance.close()
  // console.log(response)
  return response.data
}, error => {
  console.log('TCL: error', error)
  const msg = error.Message !== undefined ? error.Message : ''
  Message({
    message: 'Network error' + msg,
    type: 'error',
    duration: 3 * 1000
  })
  loadingInstance.close()
  return Promise.reject(error)
})

The specific interceptor logic depends on the specific business. I don't have any logic here, I just added a global loading.

Step 2: Encapsulate the request

Here I create another request.js, which contains the specific request.

import {Service} from './Service'
export function getConfigsByProductId(productId) {
  return Service({
    url: '/manager/getConfigsByProductId',
    params: { productId: productId }
  })
}
export function getAllAndroidPlugins() {
  return Service({
    url: '/manager/getAndroidPlugin ',
    method: 'get'
  })
}
export function addNewAndroidPlugin(data) {
  return Service({
    url: '/manager/addAndroidPlguin',
    data: JSON.stringify(data)
  })
}

Of course, you can also encapsulate the URL again and put it in another file. I think this is meaningless and will increase the complexity. The main thing to pay attention to here is the naming problem. It is recommended to name it according to the function. For example, here I use request method + function or content + parameters. In this way, the name getConfigsByProductId is also very clear.

Step 3: Use

In the vue component

import {getAllAndroidPlugins,getConfigsByProductId,addNewAndroidPlugin} from '@/api/request.js'

getAllAndroidPlugins()
.then(res=>{

})

Global use in main.js

import {Service} from '@/api/Service.js'
Vue.prototype.$axios=Service

Advanced version

With the upgrade of vue cli, core-js\babel and other dependencies have also been upgraded. Now you can use async/await as you like. Therefore, this encapsulation is to upgrade the previous Promise to async await. First, it is still the same. Encapsulate axios first

//Service.js
import axios from 'axios'
const ConfigBaseURL = 'https://localhost:3000/' //Default path, you can also use env to determine the environment //Use the create method to create an axios instance export const Service = axios.create({
  timeout: 7000, // Request timeout baseURL: ConfigBaseURL,
  method: 'post',
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})
// Add request interceptor Service.interceptors.request.use(config => {
  return config
})
// Add response interceptor Service.interceptors.response.use(response => {
  // console.log(response)
  return response.data
}, error => {
  return Promise.reject(error)
})

At this point you have obtained an axios object, and then I recommend a commonly used library, mainly used to handle async errors: await-to-js. The code is continued from above.

import to from 'await-to-js'
export function isObj(obj) {
  const typeCheck = typeof obj!=='undefined' && typeof obj === 'object' && obj !== null 
  return typeCheck && Object.keys(obj).length > 0
}
export async function _get(url, qs,headers) {
  const params = {
    url,
    method: 'get',
    params: qs ? qs : ''
  }
  if (headers) { params.headers = headers }
  const [err, res] = await to(Service(params))
  if (!err && res) {
    return res
  } else {
    return console.log(err)
  }
}

When encapsulating get, you only need to consider parameter, use await-to-js to capture errors during await, return data only when successful, and use the interceptor when an error occurs.

export async function _get(url, qs,headers) {
  const params = {
    url,
    method: 'get',
    params: isObj(qs) ? qs : {}
  }
  if (isObj(headers)) {params.headers = headers}
  const [err, res] = await to(Service(params))
  if (!err && res) {
    return res
  } else {
    return console.log(err)
  }
}

This is the post I packaged

export async function _post(url, qs, body) {
  const params = {
    url,
    method: 'post',
    params: isObj(qs) ? qs : {},
    data: isObj(body) ? body : {}
  }
  const [err, res] = await to(Service(params))
  if (!err && res) {
    return res
  } else {
    return console.log(err)
  }
}

It can be directly introduced when used, or it can be encapsulated multiple times

//a.vue
<script>
import{_get}from './Service'
export default{
	methods:{
    	async test(){
        const res = await _get('http://baidu.com')
       }
    }
}
</script>

The above is the details of several methods of Vue encapsulating Axios. For more information about Vue encapsulating Axios, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed example of using typescript to encapsulate axios in Vue3
  • How to encapsulate axios in Vue
  • How to simply encapsulate axios in vue
  • How to encapsulate axios request with vue
  • Detailed explanation of AXIOS encapsulation in Vue

<<:  Docker Swarm from deployment to basic operations

>>:  Centos7.5 installs mysql5.7.24 binary package deployment

Recommend

Detailed explanation of mysql.user user table in Mysql

MySQL is a multi-user managed database that can a...

MySQL controls the number of attempts to enter incorrect passwords

1. How to monitor MySQL deadlocks in production e...

CentOS8 - bash: garbled characters and solutions

This situation usually occurs because the Chinese...

Canonical enables Linux desktop apps with Flutter (recommended)

Google's goal with Flutter has always been to...

Understanding render in Vue scaffolding

In the vue scaffolding, we can see that in the ne...

How to understand Vue's simple state management store mode

Table of contents Overview 1. Define store.js 2. ...

Oracle VM VirtualBox installation of CentOS7 operating system tutorial diagram

Table of contents Installation Steps Environment ...

HTML+CSS3 code to realize the animation effect of the solar system planets

Make an animation of the eight planets in the sol...

How to add color mask to background image in CSS3

Some time ago, during development, I encountered ...

How to clean up data in MySQL online database

Table of contents 01 Scenario Analysis 02 Operati...

Summary of MySQL lock related knowledge

Locks in MySQL Locks are a means to resolve resou...