封装axios统一http请求对象

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 => this.instance.get('/tags');

}

export default TagsApi;

你可能感兴趣的:(封装axios统一http请求对象)