当前位置:   article > 正文

TypeScript封装微信小程序请求实战_微信小程序原生 ts 请求

微信小程序原生 ts 请求

前言
最近第一次做原生微信小程序,之前都是采用Taro、uni这两个第三方框架,发现微信原生小程序支持了TypeScript,于是尝试了使用ts结合Promise封装了微信简易请求库,不得不说,写ts确实可以减少动态语言(JS)带来的bug,如下:

const host = 'xxx';

/**
 * http请求配置
*/
interface RequestConfig {
    url: String;
    method?: HttpMethod;
    data?: any;
    needToken?: Boolean;
    header?: Object
}

/**
 * http请求方法枚举
*/
enum HttpMethod {
    GET,
    POST
}


class HttpRequest {

    private static instance: HttpRequest;

	private constructor() {}

    /**
     * 单例
    */
    public static getInstance(): HttpRequest {
        if (!this.instance) {
            this.instance = new HttpRequest();
        }
		
        return this.instance;
    }



	/**
	 * 公用请求方法
	*/
	public request(requestConfig: RequestConfig): Promise<Object> {
        return new Promise((resolve, reject) => {
            let header = {
              'content-type': 'application/json',
			};
            wx.request({
              method: requestConfig.method === HttpMethod.GET ? "GET" : "POST",
              url: `${host}${requestConfig.url}`,
              data: requestConfig.data,
              header: Object.assign(header, requestConfig?.header),
              success:(res) => resolve(res.data),
              fail:(err) =>  reject(err),
            });
        });
    }

	/**
	 * url:请求url
	 * config: 包括请求头
	*/
    public get(url: string, config?:Object):Promise<Object> {
        return this.request({ url, method: HttpMethod.GET, ...config })
    }

    public post(url: string, data: Object, config?:Object):Promise<Object>  {
        return this.request({ url, method: HttpMethod.POST, data, ...config })
    }

}

export default HttpRequest.getInstance();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75

三种调用

import http  from 'xxx';
http({ methods: "POST",url: 'xxx', data, header });
http.post('xxx', params, { header: { 'Content-Type'= 'application/x-www-form-urlencoded'}})
http.get('xxx', config);
  • 1
  • 2
  • 3
  • 4

总结
感谢你的观看,若有写的不对、不合理的地方,希望大家指出。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/283808?site
推荐阅读
相关标签
  

闽ICP备14008679号