With the upgrade of vue CLI, dependencies such as core-js\ Babel have been upgraded, and now async/await can be used as desired, so this package is to upgrade the Promise to async await. First, as before, wrap Axios

// service. js import axios from 'axios' const ConfigBaseURL = 'https://localhost:3000/' // Default path, Export const Service = axios.create({timeout: 7000, // request timeout time baseURL: ConfigBaseURL, method: 'post', headers: { 'Content-Type': 'application/json; Charset = utf-8 '}}) / / add request interceptor Service. The interceptors. Request. Use (config = > {return config}) / / add a response to the interceptor Service.interceptors.response.use(response => { // console.log(response) return response.data }, error => { return Promise.reject(error) })Copy the code

At this point you get an AXIos object, and I recommend a common library for handling async errors :await-to-js. The code connects.

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) } }Copy the code

Encapsulate get only to consider parameters, use await-to-js to catch await errors, return data only on success, and go interceptor on error.

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) } }Copy the code

This is my wrapped post

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) } }Copy the code

When used, it can be introduced directly or packaged several times

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