await async axios

时间:2021-07-21
本文章向大家介绍await async axios,主要包括await async axios使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
import axios from 'axios'
2import Api from 'api.js'
3
4let instance = axios.creat({
5    baseURL: 'http://localhost:8080',
6    timeout: 1000
7})
8const Http = {}//包裹请求方法的容器
9
10for(let key in Api){
11    let api = Api[key]
12    Http[key] = async function(
13        params,//请求参数
14        isFormData=false,//是否是form-data请求
15        config={}//配置参数
16    ){  
17        let newParams = {}
18
19        //判断content-type是不是form-data类型
20        if(params && isFormData){
21            newParams = new FormData()
22            for(let i in params){
23                newParams.append(i,params[i])
24            }
25        }else newParams = params
26
27        //不同请求的判断
28        let res = {}
29        if(api.method === 'put' || api.method === 'post' || api.method === 'patch'){
30            try{
31                res = await instance[api.method](api.url,newParams,config)
32            }catch(err){
33                res = err
34            }
35        }else if(api.method === 'delete' || api.method === 'get'){
36            config.params = newParams
37            try{
38                res = await instance[api.method](api.url,config)
39            }catch(err){
40                res = err
41            }
42        }
43        return res //返回响应值
44    }
45}
46//请求拦截器
47instance.interceptors.request.use(
48    config => {
49        //发起请求前
50        Toast.loading()
51        return config
52    },
53    err => {
54        //请求错误
55        Toast.clear()
56        return err
57    }
58)
59//响应拦截器
60instance.interceptors.response.use(
61    res => {
62        //响应前
63        Toast.clear()
64        return res.data
65    },
66    err => {
67        //响应错误
68        Toast.clear()
69        return err
70    }
71)
72
73export default Http

调用方法

 1import Http from 'http.js'
2Vue.prototype.$Http = Http
3
4async function(){
5    let res = await this.$Http.api1({id: 4})
6}
7
8async function(){
9    let res = await this.$Http.api2(info,true,config)
10}

原文地址:https://www.cnblogs.com/SunshineKimi/p/15039297.html