美文网首页
小程序中用TS封装一个http插件

小程序中用TS封装一个http插件

作者: supa同学 | 来源:发表于2020-08-18 09:06 被阅读0次
    import Taro from '@tarojs/taro'
    import config from '../config/config'
    import qs from 'qs'
    
    const dev = process.env.NODE_ENV === 'development'
    
    class Http {
      BASEURL:String
      private static instance: Http;
    
      public constructor () {
        this.BASEURL = config.baseUrl
      }
    
      public static getInstance(): Http {
        if (!this.instance) {
            this.instance = new Http();
        }
        return this.instance;
      }
    
      request(api: string, data?: object, showLoading:boolean = true, method: 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT' = 'POST') {
        if(showLoading){
          Taro.showLoading({
            title: 'Loading...'
          })
        }
        if(false){
          console.log('=======请求参数==========================================')
          console.log(data)
          console.log(`接口地址:${this.BASEURL + api}`)
        }
    
        let cookie = Taro.getStorageSync('JSESSIONID')
        return new Promise((resolve, reject) => {
          Taro.request({
            url: `${this.BASEURL + api}`,
            method,
            data: qs.stringify(data),
            credentials: 'include',
            header: {
              'Cookie': 'bookkeeping-session='+ cookie,
              'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
            }
          }).then((res:any) => {
            if (!dev) {
              if (res.data.message === '代理商未登录,请先登录') {
                window.location.href = '/h5/index.html#/pages/login'
              }
            }
            if (res.message === '未登录') {
              Taro.removeStorageSync('userinfo')
              Taro.switchTab({
                url: `/pages/index/index`
              })
            }
            if(false){
              console.log('=======返回数据======')
              console.log(res.data)
            }
           showLoading && Taro.hideLoading()
            resolve(res.data)
            if (!res.data.success) {
              Taro.showToast({
                title: res.data.message,
                icon: 'none',
                duration: 3000
              })
            }
          })
        })
      }
    
    }
    let http = Http.getInstance()
    export default http;
    
    
    使用方式
    http.request(api.addBudgetPage)
      .then((res:any)=>{
        if(res.success){
           ...
        }
    })        
    

    相关文章

      网友评论

          本文标题:小程序中用TS封装一个http插件

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