美文网首页
封装axios统一http请求对象

封装axios统一http请求对象

作者: 梁某人的剑 | 来源:发表于2020-07-03 18:40 被阅读0次

http-clients

import axios, {AxiosInstance, AxiosResponse} from 'axios';

export abstract class HttpClient {
    protected readonly instance: AxiosInstance;

    protected constructor(baseURL: string) {
        this.instance = axios.create({
            baseURL,
            headers: {'Content-Type': 'application/json'},
        });

        this._initializeResponseInterceptor();
    }

    private _initializeResponseInterceptor = () => {
        this.instance.interceptors.response.use(
            this._handleResponse,
            this._handleError,
        );
    };

    private _handleResponse = (res: AxiosResponse) => res.data.data || res.data;

    protected _handleError = (error: any) => Promise.reject(error);
}

tags-http-client

import {HttpClient} from '../http-client';
import {Tag} from '../types';
import {AxiosRequestConfig} from "axios";

class TagsApi extends HttpClient {
    public constructor() {
        super('http://localhost:3000');

        this._initializeRequestInterceptor();
    }

    private _initializeRequestInterceptor = () => {
        this.instance.interceptors.request.use(
            this._handleRequest,
        );
    };

    private _handleRequest = (config: AxiosRequestConfig) => {
        config.headers['Authorization'] = 'Bearer ...';
        return config;
    };

    public getTags = (): Promise<any> => this.instance.get<Tag[]>('/tags');

}

export default TagsApi;

相关文章

网友评论

      本文标题:封装axios统一http请求对象

      本文链接:https://www.haomeiwen.com/subject/snheqktx.html