axios ts版本

478 阅读1分钟

安装axios

 npm install axios

统一封装axios请求 index.ts

import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios'
import type { Result } from '@/common/interface/Result';
import { RequestEnums } from '@/common/enums/httpEnums';
const URL: string = '/api';


const config = {
    baseURL: URL as string,
    timeout: RequestEnums.TIMEOUT as number,
    withCredentials: true
}

class RequestHttp {
    service: AxiosInstance;
    public constructor(config: AxiosRequestConfig) {
        this.service = axios.create(config);
        /*** 请求拦截器 */
        this.service.interceptors.request.use(
            (config: AxiosRequestConfig) => {
                const token = localStorage.getItem('token') || '';
                return {
                    ...config,
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
                        'token': token,
                    }
                }
            },
            (error: AxiosError) => {
                // 请求报错
                Promise.reject(error)
            }
        )

        /**响应拦截器*/
        this.service.interceptors.response.use(
            (response: AxiosResponse) => {
                const { data, config } = response; // 解构
                if (data.code === RequestEnums.OVERDUE) {
                    // 登录信息失效,应跳转到登录页面,并清空本地的token
                    localStorage.setItem('token', '');
                    // router.replace({
                    //   path: '/login'
                    // })
                    return Promise.reject(data);
                }
                // 全局错误信息拦截(防止下载文件得时候返回数据流,没有code,直接报错)
                if (data.code && data.code !== RequestEnums.SUCCESS) {
                    // ElMessage.error(data); // 此处也可以使用组件提示报错信息
                    return Promise.reject(data)
                }
                return data;
            },
            (error: AxiosError) => {
                const { response } = error;
                if (response) {
                    this.handleCode(response.status)
                }
                if (!window.navigator.onLine) {
                    // ElMessage.error('网络连接失败');
                    // 可以跳转到错误页面,也可以不做操作
                    // return router.replace({
                    //   path: '/404'
                    // });
                }
            }
        )
    }

    handleCode(code: number): void {
        switch (code) {
            case 401:
                // ElMessage.error('登录失败,请重新登录');
                break;
            default:
                // ElMessage.error('请求失败');
                break;
        }
    }

    // 常用方法封装
    get<T>(url: string, params?: object): Promise<Result<T>> {
        return this.service.get(url, { params });
    }
    post<T>(url: string, params?: object): Promise<Result<T>> {
        return this.service.post(url, params);
    }
    put<T>(url: string, params?: object): Promise<Result<T>> {
        return this.service.put(url, params);
    }
    delete<T>(url: string, params?: object): Promise<Result<T>> {
        return this.service.delete(url, { params });
    }
}

// 导出一个实例对象
export default new RequestHttp(config);  

Result.ts

export interface Result<T = any> {
    code: number;
    message: string;
    datas: T;
}

httpEnums.ts

export enum RequestEnums {
  TIMEOUT = 20000, // 超时
  FAIL = 500, // 请求失败
  SUCCESS = 200, // 请求成功
  OVERDUE = 304, // 登入失败
}

使用

import axios from '@/utils/http/axios/index'
import { LoginReqForm } from '@/api/params/LoginParams';
import { Result } from '@/common/interface/Result';


export const loginApi = (params: LoginReqForm) => {
    return axios.post<Result>('/login.do', params);
}
import { ref, reactive, defineComponent } from "vue";
import { LoginReqForm } from "@/api/params/LoginParams";

const loginForm: LoginReqForm = reactive({
  username: "1011",
  password: "123456",
});

const Login = async () => {
    const data = await loginApi(loginForm);
    console.log(data);
};

跨域 vite.config.ts

export default ({ mode }) => {
	return defineConfig({
		server: {
			host: '0.0.0.0',
			port: 3000,
			open: true,
			proxy: {
				"/api": {
					target: env.VITE_BASE_API,
					changeOrigin: true,
					rewrite: (path) => path.replace(/^\/api/, '/')
				}
			}
		},
	})

}