当前位置:   article > 正文

在vue3.0+ts中axios比较好的封装_vue3.0+ts 封装接口

vue3.0+ts 封装接口

常见的封装有五个步骤:

  1. 引入axios
  2. 配置axios基本配置,比如baseUrl,headers,timeout
  3. 请求拦截
  4. 响应拦截
  5. 进行二次封装

在http文件夹得index.ts中

// 1. 引入axios
import axios from 'axios'

enum MESS {
    "操作成功" = 200,
    "密码错误" = 401,
    "账号错误" = 402,
    "请求异常" = 404
}

// 2. 配置axios基本配置,比如baseUrl,headers,timeout
const $http = axios.create({
    timeout:3000,
    headers:{
        "Content-Type":"application/json;chartset=utf-8"
    }
})

// 3. 请求拦截
$http.interceptors.request.use(config => {
    config.headers = config.headers || {};
    // config.headers.token = 
    return axios
})

// 4. 响应拦截
$http.interceptors.response.use(res => {
    const code:number = res.data?.code;
    if(code !=200) {
        alert(MESS[code]);
        return Promise.reject(res.data)
    } else {
        return res.data
    }
},err => {
    console.log(err);
})
// 5. 进行二次封装
export default $http

  • 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

在sever.ts中

import $http from ".";

export const test = (data:any):any => {
    return $http({
        url:'/test',
        method:'GET',
        params:data
    })
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

最后在页面中import引用即可

待完善~

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

闽ICP备14008679号