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

js to achieve the pop-up effect

This article example shares the specific code of ...

In-depth explanation of slots and filters in Vue

Table of contents Slots What are slots? Slot Cont...

Modify the default scroll bar style in the front-end project (summary)

I have written many projects that require changin...

Nofollow makes the links in comments and messages really work

Comments and messages were originally a great way...

How to avoid garbled characters when importing external files (js/vbs/css)

In the page, external files such as js, css, etc. ...

Solve the problem that Docker pulls MySQL image too slowly

After half an hour of trying to pull the MySQL im...

Use of Linux chkconfig command

1. Command Introduction The chkconfig command is ...

CentOS7 uses rpm package to install mysql 5.7.18

illustrate This article was written on 2017-05-20...

Vue.js style layout Flutter business development common skills

Correspondence between flutter and css in shadow ...

How to use Dayjs to calculate common dates in Vue

When using vue to develop projects, the front end...

Introduction to HTML DOM_PowerNode Java Academy

What is DOM? With JavaScript, you can reconstruct...

Docker Stack deployment method steps for web cluster

Docker is becoming more and more mature and its f...