首页 > 其他分享 >ts封装axios

ts封装axios

时间:2022-08-13 19:45:45浏览次数:76  
标签:axios 封装 ts instance import config options const

1.封装请求

//存放请求路径的文件
import urlConfig from '../api/index'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import router from '@/router';
class Request {
    private baseUrl: string = urlConfig.Base_URL

    private request(opts: {}) {
        const instance: AxiosInstance = axios.create({
            baseURL: this.baseUrl,
            timeout: 3000
        })
        this.setInterceptors(instance)
        return instance(opts)
    }
    //拦截器
    private setInterceptors(instance: AxiosInstance) {
        //请求拦截器
        instance.interceptors.request.use((config) => {

            const token = localStorage.getItem('token')
            if (token && config.headers) {
                config.headers['Authorization'] = token;
            }
            return config
        })
        //响应拦截器
        instance.interceptors.response.use((res: AxiosResponse) => {
            if (res.status == 200) {
                return Promise.resolve(res.data)
            } else {
                return Promise.reject(res.data)
            }
        }, err => {
            switch (err.response.status) {
                case 401:
                    const instance = ElMessage.error('用户信息过期,请重新登录');
                    setTimeout(() => {
                        instance.close();
                        router.push('/login');
                    }, 1000);
                    break;
                default:
                    console.warn(`status= ${status}`);
                    break;
            }
            return Promise.reject(err);
        })
    }
//封装get请求 public get(url: string, options?: AxiosRequestConfig) { return this.request({ url: url, method: 'get', params: options }) }
//封装post请求 public post(url: string, options: AxiosRequestConfig) { return this.request({ url: url, method: 'post', headers: { 'Content-Type':'application/x-www-form-urlencoded' }, data: options }) } } export const httpRequest = new Request()

2.请求使用案例

将请求封装成函数

import { httpRequest as axios } from '../untils/request'
//接口地址 ‘/api/test’
import config from './config/user'
export const login: Function = (options: {}) => axios.post(config.loginApi, options)
export const test:Function = (options:{}|undefined)=>axios.get(config.test,options)

导入接口

import { login } from '../api/user'
async function loginClick() {
    let data = new FormData()
    data.append('username', account.value)
    data.append('password', password.value)
    const response = await login(data)
    console.log('response :>> ', response);
    if(response.status==0){
        localStorage.setItem('token',response.token)
        router.push('/home')
    }
}

 

标签:axios,封装,ts,instance,import,config,options,const
From: https://www.cnblogs.com/cstd/p/16583873.html

相关文章

  • vue echarts 宽度100% 显示不正常
    varchartDom=document.getElementById("chartDom");varoption={};varmyChart=echarts.init(chartDom);option&&myChart.setOption(opt......
  • U盘安装ubuntu18.04 LTS图文详细过程(转)
    原文:https://blog.csdn.net/u014453443/article/details/88049804制作U盘引导盘,安装Ubuntu18.04LTS系统一、下载Ubuntu18.04LTS系统的iso文件镜像下载地址https://ww......
  • 10.Matplotlib subplots()函数详解
    matplotlib.pyplot模块提供了一个subplots()函数,它的使用方法和subplot()函数类似。其不同之处在于,subplots()既创建了一个包含子图区域的画布,又创建了一个figure......
  • CF1208F Bits And Pieces
    传送门思路面对位运算,而且要求答案最大,我们应该想到一个贪心:从二进制最高位开始取,这样能保证答案最优对于一个答案\(x\),它可行当且仅当存在\(i<j<k\),满足有\(x\opl......