2个月前端经验对请求的封装

54 阅读1分钟

UserProviderApi.ts

import httpClient, {type ResData} from '@/providers/httpClient'
import type {LoginDO} from "@/providers/do/user";

export class UserProviderApi {

    loginByParams(query_params: string): Promise<ResData<LoginDO>> {
        return httpClient.post('/user/loginQuick', {
            'auth': query_params
        })
    }
}

httpClient.ts

import httpConfigs from "@/providers/httpConfigs";
import {RequestHttpBuilder} from "@/utils/axiosUtils";
import type {AxiosRequestConfig} from "axios";
import {AuthorizationHandler} from "@/providers/interceptor/authorizationHandler";
import {BaseResponseHandler} from "@/providers/interceptor/baseResponseHandler";


export interface ResData<T> {
    code: number
    data?: T
    msg?: string
}


const authorizationHandler = new AuthorizationHandler(httpConfigs);

const client = new RequestHttpBuilder()
    .config({
        // 设置超时时间
        timeout: 20000,
        // 跨域时候允许携带凭证
        withCredentials: true
    } as AxiosRequestConfig)
    // 请求处理
    .addRequestHandler(authorizationHandler)
    // 响应处理
    .addResponseHandler(new BaseResponseHandler())
    // 响应错误拦截处理
    .addResponseRejectHandler(authorizationHandler)
    .build()

export default client