ts + axios封装

本文介绍了如何使用TypeScript封装axios请求,包括get和post方法,以及响应结果的处理,重点讲述了错误处理策略和约定的接口返回格式。

https.ts文件

/**
 * @author  作者
 * @time    2020-9-27 8:47
 * @title   http请求封装
 * desc 前后端约定接口返回解构规范
 * {
 *    code: '1',
 *    data:" 请求成功",
 *    message: ""
 * }
 */
import { Interceptor } from './interceptor';
import { message, Modal } from 'ant-design-vue';
import qs from 'qs';

export class Http {
    public axios: any;


    constructor() {
        // 获取axios实例
        this.axios = new Interceptor().getInterceptors();
    }

    /**
     * get请求
     * @param {String} url [请求的url地址]
     * @param {object} params [请求时携带的参数, 默认为空]
     * @param {boolean} download [判断是否是下载请求, 默认为否]
     * @param {boolean} loading [判断是否是需要loading, 默认为否]
     * @desc 由于loading不能一成不变全屏加载,很多种情况都是局部loading,所以当loading为true时,会返回整个response,以便自行处理loading。
     */
    public getData(url: string, params: object = {}, download: boolean = false, loading: boolean = false) {

        return new Promise((resolve, reject) => {
            const config: any = { params };

            if (download) {
                config.responseType = 'blob';
            }

            this.axios.get(url, {
                ...config,
            }).then((res: any) => {
                this.resultHandle(res, resolve, loading);
            }).catch((err: { message: any; }) => {
                reject(err.message);
            });
        });

    }


    /**
     * post请求
     * get请求
     * @par
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夜丶陌颜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值