当前位置:   article > 正文

vue3 +ts 如何安装封装axios_vue3 ts axios

vue3 ts axios

在这里插入图片描述


vite创建的项目,vue3使用axios。
使用ts二次封装axios访问接口,并调用接口。

vue3安装封装axios,其实和vue2的大差不差。只是在ts和js上,有些区别。

为什么封装axios

  1. 求头能统一处理
  2. 便于接口的统一管理
  3. 解决回调地狱
  4. 配置拦截器,给不同的实例配置不同的拦截器,支持以对象形式接受多个拦截器配置

安装axios

npm install axios
  • 1

引入插件

在使用的文件中引入

import axios from "axios";
  • 1

封装request

封装方法一:

先在 src 下创建一个 utils文件夹,并添加一个 request.ts 文件

import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'

class HttpRequest {
    private readonly baseUrl: string;
    constructor() {
        this.baseUrl = 'http://localhost:8080'
    }
    getInsideConfig() {
        const config = {
            baseURL: this.baseUrl,// 所有的请求地址前缀部分(没有后端请求不用写)  
            timeout: 80000, // 请求超时时间(毫秒)
            withCredentials: true,// 异步请求携带cookie
            // headers: {
            // 设置后端需要的传参类型
            // 'Content-Type': 'application/json',
            // 'token': x-auth-token',//一开始就要token
            // 'X-Requested-With': 'XMLHttpRequest',
            // },
        }
        return config
    }

    // 请求拦截
    interceptors(instance: AxiosInstance, url: string | number | undefined) {
        instance.interceptors.request.use(config => {
            // 添加全局的loading..
            // 请求头携带token
            return config
        }, (error: any) => {
            return Promise.reject(error)
        })
        //响应拦截
        instance.interceptors.response.use(res => {
            //返回数据
            const { data } = res
            console.log('返回数据处理', res)
            return data
        }, (error: any) => {
            console.log('error==>', error)
            return Promise.reject(error)
        })
    }

    request(options: AxiosRequestConfig) {
        const instance = axios.create()
        options = Object.assign(this.getInsideConfig(), options)
        this.interceptors(instance, options.url)
        return instance(options)
    }
}

const http = new HttpRequest()
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
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53

封装方法二:

request.ts文件

import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'
import { baseURL_dev } from '@/config/baseURL';

class HttpRequest {
    private readonly baseUrl: string;
    constructor() {
        this.baseUrl = baseURL_dev+"/api"
    }
    getInsideConfig() {
        const config = {
            baseURL: this.baseUrl,
            timeout: 30000, 
            headers: {
                'Content-Type': 'application/json; charset=utf-8',
                'Authorization': '913ed069-8194-4119-a036-ad20e7090171'
            },
        }
        return config
    }

    // 请求拦截
    interceptors(instance: AxiosInstance, url: string | number | undefined) {
        instance.interceptors.request.use((config: any) => {
            // 添加全局的loading..
            // 请求头携带token
            return config
        }, (error: any) => {
            return Promise.reject(error)
        })
        // //响应拦截
        instance.interceptors.response.use((res: any) => {
            // debugger;
            const { data } = res
            console.log('返回数据处理', res)
            return data
        }, (error: any) => {
            console.log('error==>', error)
            return Promise.reject(error)
        })
    }

    request(options: AxiosRequestConfig) {
        const instance = axios.create()
        options = Object.assign(this.getInsideConfig(), options)
        this.interceptors(instance, options.url)
        return instance(options)
    }
}

const http = new HttpRequest()
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
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

baseURL.ts文件

export const baseURL_dev = 'http://api...';
export const baseURL_pro = 'http://api...';
export const baseURL_test = 'http://api...';
  • 1
  • 2
  • 3

封装方法三:

request.ts文件

import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'
import { baseURL_dev } from '@/config/baseURL';
import { useRouter } from 'vue-router';
const router = useRouter();// 当前页面的路由对象




class HttpRequest {
    private readonly baseUrl: string;
    constructor() {
        this.baseUrl = baseURL_dev + "/api"
    }
    getInsideConfig() {
        let token = localStorage.getItem('Token')
        if (token) {
            token = 'Bearer ' + token
            console.log(token, 'token1');
        
        } else {
            // router.push('/');
            token = '913ed069-8194-4119-a036-ad20e7090171';
            console.log(token, 'token2');
        
        }
        const config = {
            baseURL: this.baseUrl,
            timeout: 30000,
            headers: {
                'Content-Type': 'application/json; charset=utf-8',
                'Authorization': token
            },
        }
        return config
    }

    // 请求拦截
    interceptors(instance: AxiosInstance, url: string | number | undefined) {
        instance.interceptors.request.use((config: any) => {
            // 添加全局的loading..
            // 请求头携带token
            return config
        }, (error: any) => {
            return Promise.reject(error)
        })

        // //响应拦截
        instance.interceptors.response.use((res: any) => {
            // debugger;
            const { data } = res
            console.log('返回数据处理', res)
            return data
        }, (error: any) => {
            console.log('error==>', error)
            if (error.response && error.response.status === 401) {
                // 尝试从本地存储获取新的token  
                const newToken = localStorage.getItem('Token');

                if (newToken) {
                    // 设置新的token到请求头中  
                    // instance.defaults.headers.common['Authorization'] = `Bearer ${newToken}`;
                    localStorage.removeItem('Token')
                    // localStorage.removeItem('token_type')
                    router.push({ path: '/login' })
                } else {
                    // 如果没有新token,清除旧的token并跳转到登录页  
                    localStorage.removeItem('Token');
                    router.push('/login');
                }
            } else if (error.code == 403 || error.code == 401 || error.code == 404 || error.code == 500 || error.code == 502) {
                router.push('/404')
            }

            // window.location.reload();
            // return Promise.reject(error)
        })
    }

    request(options: AxiosRequestConfig) {
        const instance = axios.create()
        options = Object.assign(this.getInsideConfig(), options)
        this.interceptors(instance, options.url)
        return instance(options)
    }
}

const http = new HttpRequest()
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
  • 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

封装接口

在api的文件夹中,新建一个api的ts文件。

注意:​​因为get请求的参数需要params,它是即将与请求一起发送的 URL 参数,为了简写采用了ES6的解构,就是把下面的 params 解构,只有get 请求需要加多一层params

其它请求,如 post 等请求等就不用解构,形参是什么都行。

案例

src文件夹下新建api文件夹,新建api.ts文件,里面写你请求后台的接口,比如我这里的请求地址是/test, 加上axios的baseURL,完整的请求路径就是http://localhost:8080/test

import http from '../utils/request'
//get有值
export function getTest(params: any) {
  return http.request({
    url: '/test',
    method: 'get',
    params
  })
}

//get无值
export function (params: any) {
  return http.request({
    url: '/test',
    method: 'get',
    params
  })
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

使用

请求的组件上使用

import { ref, onMounted } from "vue";
import { getFileList } from "../../api/index";

export default {
  setup() {
    onMounted(() => {
      getTest().then((res: any) => {
        console.log(res);
      });
    });
  },
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/719602
推荐阅读