vue3 +ts 如何安装封装axios

17 篇文章 0 订阅

在这里插入图片描述


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

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

为什么封装axios

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

安装axios

npm install axios

引入插件

在使用的文件中引入

import axios from "axios";

封装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

封装方法二:

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

baseURL.ts文件

export const baseURL_dev = 'http://api...';
export const baseURL_pro = 'http://api...';
export const baseURL_test = 'http://api...';

封装方法三:

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

封装接口

在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
  })
}

使用

请求的组件上使用

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

export default {
  setup() {
    onMounted(() => {
      getTest().then((res: any) => {
        console.log(res);
      });
    });
  },
};
  • 11
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 17
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奶糖 肥晨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值