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

ts封装axios

作者:互联网

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
来源: https://www.cnblogs.com/cstd/p/16583873.html