当前位置:   article > 正文

【axios】封装axios

封装axios

一、axios简介

定义

Axios 是一个基于 promiseHTTP 库,可以用在浏览器和 node.js 中。(本文围绕XHR)

axios提供两个http请求适配器,XHRHTTP
XHR的核心是浏览器端的XMLHttpRequest对象;
HTTP的核心是nodehttp.request方法。

可以先熟悉一下axios官方文档

特性

  1. 从浏览器中创建XMLHttpRequests
  2. 从node.js创建http请求
  3. 支持promise API
  4. 拦截请求与响应
  5. 转换请求数据与响应数据
  6. 取消请求
  7. 自动转换JSON数据
  8. 客户端支持防御XSRF

简单使用

import axios from 'axios';

// 为给定ID的user创建请求 
axios.get('/user?ID=12345')   
    .then(function (response) {     
        console.log(response);   
    })   
    .catch(function (error) {    
        console.log(error);   
    });  
    
// 上面的请求也可以这样做 
axios.get('/user', { params: {ID: 12345} })   
    .then(function (response) {     
        console.log(response);   
    })   
    .catch(function (error) {     
        console.log(error);   
    });

// 支持async/await用法
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

二、为什么要封装axios? 如何封装?

axios的API很友好,可以在项目中直接使用。
但是在大型项目中,http请求很多,且需要区分环境, 每个网络请求有相似需要处理的部分,不封装会导致代码冗余,破坏工程的可维护性扩展性
axios封装没有一个绝对的标准,且需要结合项目中实际场景来设计。

通用请求应该具备什么

  1. 正常请求该有的(跨域携带cookie,token,超时设置)
  2. 请求/响应拦截器
  • 请求成功,业务状态码200,能解析result给我,不用一层一层的去判断拿数据

  • 请求失败,业务状态码非200,说明逻辑判断这是不成功的,全局message提示服务端的报错

  • http请求非200, 说明http请求都有问题,也全局message提示报错

  • http请求或者业务状态码401都做注销操作

  1. 统一文件下载处理

  2. 全局的loading配置, 默认开启,可配置关闭(由于后端的问题,经常会让前端加防抖节流或者loading不让用户在界面上疯狂乱点)

请求头

常见以下三种

(1)application/json

参数会直接放在请求体中,以JSON格式的发送到后端。这也是axios请求的默认方式。这种类型使用最为广泛。
在这里插入图片描述

(2)application/x-www-form-urlencoded

请求体中的数据会以 普通表单形式(键值对) 发送到后端。
在这里插入图片描述

(3)multipart/form-data

参数会在请求体中,以标签为单元,用分隔符(可以自定义的boundary)分开。既可以上传键值对,也可以上传文件。通常被用来上传文件的格式
在这里插入图片描述

封装例子
import _Vue from 'vue';
import axios, { AxiosInstance, AxiosResponse, AxiosRequestConfig } from 'axios';
import { CryptUtil } from '@/utils/CryptUtil';
// import { MAINHOST, QAHOST, commonParams } from '@/config';
// import { getToken } from '@/utils/common';
// import qs from 'qs';
import router from '@/router'

class AxiosHttpRequest {
  private axios: AxiosInstance;
  private dischargedApi: Array<string> = [
    '/system/api/searchHumanName',
    '/system/api/login',
    '/system/api/template',
    '/system/api/info/sysconfig/item',
    '/system/api/unitinfo/loadaddress'
  ]

  constructor(ax: any) {
    this.axios = ax;
    // axios 配置
    this.axios.defaults.timeout = 120 * 1000;
    // this.axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? MAINHOST : QAHOST;
    // @ts-ignore
    this.axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
    // this.axios.defaults.baseURL = 'http://119.3.251.200:8097';

    // http request 拦截器
    this.axios.interceptors.request.use(
      (config: AxiosRequestConfig) => {
        // 在此处添加请求头等,如添加token
        if (sessionStorage.getItem('token')) {
          // @ts-ignore
          config.headers['Authorization'] = sessionStorage.getItem('token');
          // @ts-ignore
          config.headers['Verify'] = CryptUtil.desEncrypt(new Date().getTime() + '');
        } else {
          // @ts-ignore
          if (this.dischargedApi.includes(config.url)) {
            // @ts-ignore
            config.headers['Authorization'] = 'eyJhbGciOiJIUzUxMiJ9.eyJISSI6LTEsIlVJIjoxLCJITiI6IumZtuaYjum-mSIsIlJJIjoiIiwiVU4iOiLlub_opb_lo67ml4_oh6rmsrvljLoiLCJVQyI6Ii8xLyJ9.DAWCZpyQSAngIv4NBIxxz19mrLGvHdZI8WdNim5wlI0yZoa0WkHCrb-tyDY4v1MpbpEl4TWEOndnZmxxdma0YQ';
            // @ts-ignore
            config.headers['Verify'] = CryptUtil.desEncrypt(new Date().getTime() + '');
          }
        }

        let sysConfigMap = JSON.parse(sessionStorage.getItem('sysConfigMap') as string);
        if (sysConfigMap) {
          let WEB_API_ENCRYPT_LIST = JSON.parse(sessionStorage.getItem('sysConfigMap') as string).WEB_API_ENCRYPT_LIST || [];
          if (WEB_API_ENCRYPT_LIST.length > 0) {
            WEB_API_ENCRYPT_LIST = WEB_API_ENCRYPT_LIST.split(';');
            for (let i = 0; i < WEB_API_ENCRYPT_LIST.length; i++) {
              // @ts-ignore
              if (config.url.indexOf(WEB_API_ENCRYPT_LIST[i]) > -1) {
                // @ts-ignore
                config.headers['encry'] = 'true';
                config.data = { data: CryptUtil.desEncrypt(JSON.stringify(config.data)) }
                break;
              }
            }

          }
        }

        return config;
      },
      (error: any) => {
        return Promise.reject(error);
      }
    );

    // http response 拦截器
    this.axios.interceptors.response.use(
      (response: AxiosResponse) => {
        if (response.headers['encry'] === 'true') {
          // @ts-ignore
          response.data['data'] = JSON.parse(CryptUtil.desDecrypt(response.data.data));
        }
        return response;
      },
      (error: any) => {
        if (error.response.data?.message) {
          error.message = error.response.data.message;
        } else if (error && error.response) {
          switch (error.response.status) {
            case 400: error.message = '请求错误(400)'; break;
            case 401: error.message = '未授权,请重新登录(401)'; break;
            case 403: error.message = '拒绝访问(403)'; break;
            case 404: error.message = `请求地址错误: ${error.response.config.url}`; break;
            case 405: error.message = '请求方法未允许(405)'; break;
            case 408: error.message = '请求超时(408)'; break;
            case 500: error.message = '服务端内部错误(500)'; break;
            case 501: error.message = '服务未实现(501)'; break;
            case 502: error.message = '网络错误(502)'; break;
            case 503: error.message = '服务不可用(503)'; break;
            case 504: error.message = '网络超时(504)'; break;
            case 505: error.message = 'HTTP版本不受支持(505)'; break;
            default: error.message = `连接错误: ${error.message}`;
          }
        } else if (error.message.includes('timeout')) {
          error.message = '请求超时';
        } else {
          // error.message = '连接服务器失败,请联系管理员';
        }
        if (error && error.response && (error.response.status === 401 || error.response.status === 403)) {
          _Vue.prototype.$message.warning({
            content: "token失效,请重新登录",
            duration: 3,
            onClose: () => {
              // 清除token
              sessionStorage.clear();
              // window.close();
              router.push({ name: 'Login' });
            }
          });
        } else {
          _Vue.prototype.$message.error(
            error.message
          );
        }
        return Promise.reject(error.response);
      }
    );
  }

  public get(url: string, params: object, config: object) {
    //增加时间戳 防止缓存
    params = {
      _t: new Date().getTime(),
      ...params
    }
    return this.axios({
      method: 'get',
      url,
      params,
      ...config,
    }).then(
      (res: any) => {
        if (res && res.data) {
          if (!res.data.ok) {
            _Vue.prototype.$message.error(
              res.data.message ? res.data.message : ""
            );
            return;
          }
          return res.data.data || res.data.dataMap;
        }
      }
    );
  }

  // 获取静态资源
  public getStatic(url: string, params: object, config: object) {
    //增加时间戳 防止缓存
    params = {
      _t: new Date().getTime(),
      ...params
    }
    return this.axios({
      method: 'get',
      url,
      params,
      ...config,
    }).then(
      (res: any) => {
        if (res && res.data) {
          return res.data;
        } else {
          _Vue.prototype.$message.error('资源获取失败!');
        }
      }
    );
  }

  public getTrace(url: string, params: object, config: object) {
    //增加时间戳 防止缓存
    params = {
      _t: new Date().getTime(),
      ...params
    }
    return this.axios({
      method: 'get',
      url,
      params,
      ...config,
    }).then(
      (res: any) => {
        if (res && res.data) {
          return res.data.data || res.data.dataMap;
        }
      }
    );
  }

  public post(url: string, params: object) {
    return this.axios({
      method: 'post',
      url,
      // data: qs.stringify(params),
      data: params,
    }).then(
      (res: any) => {
        if (res && res.data) {
          if (!res.data.ok) {
            _Vue.prototype.$message.error(
              `${res.data.message ? `${res.data.message}` : ""}`,
            );
            return;
          }
          return res.data.data || res.data.dataMap;
        }
      }
    );
  }

  public postJson(url: string, params: object, config: object, need:boolean = true) {
    return this.axios({
      method: 'post',
      url,
      data: JSON.stringify(params),
      headers: { "Content-Type": "application/json", ...config },
      transformRequest: [function (data, headers) {
        // @ts-ignore
        if (!need && headers.Authorization) {
          // @ts-ignore
          delete headers.Authorization;
        }
        // @ts-ignore
        if (!need && headers.Verify) {
          // @ts-ignore
          delete headers.Verify;
        }
        return data;
      }]
    }).then(
      (res: any) => {
        if (res && res.data) {
          if ((res.data.hasOwnProperty("success") && !res.data.success) || (res.data.hasOwnProperty("hasError") && res.data.hasError)) {
            _Vue.prototype.$Notice.error({
              title: "请求失败",
              desc: res.data.message ? res.data.message : ""
            });
            return;
          }
          return res.data.data || res.data.dataMap;
        }
      }
    );
  }

  public uploadFile(url: string, data: FormData, config1?: object) {
    let config = {
      // 请求头信息
      headers: { 'Content-Type': 'multipart/form-data' },
      ...config1
    };
    return this.axios.post(url, data, config).then(
      (res: any) => {
        if (res && res.data) {
          if (!res.data.ok) {
            _Vue.prototype.$Notice.error({
              title: "请求失败",
              desc: res.data.message ? res.data.message : ""
            });
            return;
          }
          return res.data.data || res.data.dataMap;
        }
      }
    );
  }

  public getData(url: string, params: object) {
    return this.axios({
      method: 'get',
      url,
      params: params,
      responseType: 'blob'
    }).then((res) => {
      let url = window.URL.createObjectURL(new Blob([res.data]));
      let link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      // @ts-ignore
      link.setAttribute('download', params['fileName']);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    });
  }

  public postData(url: string, fileName: string, params: object) {
    return this.axios({
      method: 'post',
      url,
      data: params,
      responseType: 'blob'
    }).then((res) => {
      let url = window.URL.createObjectURL(new Blob([res.data]));
      let link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      // @ts-ignore
      link.setAttribute('download', fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    });
  }
}

const $axios: AxiosHttpRequest = new AxiosHttpRequest(axios);
export function AxiosRequest(Vue: typeof _Vue): void {
  Vue.prototype.$axios = $axios;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
使用
async loadReportFields() {
  this.tableData = await Service.loadReportFields({ reportId: this.reportId });
}
  • 1
  • 2
  • 3
import Vue from "vue";

const config = `/report/api/config/`;
const configCond = `/report/api/config/cond/`;
const configStatis = `/report/api/config/statis/`;
const configAuth = `/report/api/config/auth/`;
const statis = `/report/api/statis/`;

export const loadReportFields = (params: any) => {
  return Vue.prototype.$axios.get(`${config}loadfields`, params);
};

export const updateReport = (params: any) => {
  return Vue.prototype.$axios.post(`${config}update`, params);
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

参考 https://juejin.cn/post/6999932338566070308#heading-12

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/305984
推荐阅读
相关标签
  

闽ICP备14008679号