美文网首页
小程序 http封装

小程序 http封装

作者: my木子 | 来源:发表于2020-04-13 14:59 被阅读0次
    const api_base_url = 'https://***';
    // 错误提示
    const tips = {
      1: '抱歉,出现了一个未知错误'
    };
    
    class HTTP {
      // 网络请求函数
      request(params) {
        if (!params.method) {
          params.method = 'GET'
        }
        wx.request({
          url: api_base_url + params.url,
          method: params.method,
          data: params.data,
          dataType:'json',
          header: {
            'content-Type': 'application/x-www-form-urlencoded',
            'accessToken': wx.getStorageSync('token') || ''
          },
          success: (res) => {
    
            let code = res.statusCode.toString()
            // 判断状态码是否以2开头
            if (code.startsWith('2') && res.data.code === 200) {
              wx.hideLoading();
              // 回调函数
              params.success(res.data)
            } else {
              this._show_error(res.data)
            }
          },
          fail: (err) => {
            this._show_error(1)
          }
        })
      }
    
      // 错误处理函数
      _show_error(res) {
        console.log(res)
        let msg = ''
        if (res.code !== 500 || !res.msg) {
          var error_code = 1
          msg = tips[error_code]
        }else{
          msg = res.msg
        }
        wx.showToast({
          title: msg,
          icon: 'none',
          duration: 2000
        })
      }
    }
    
    export {
      HTTP
    }
    
    // 示例
    import {HTTP} from '../../utils/request.js';
    let http = new HTTP();
    // js
      getList: function () {
        http.request({
          url: '/list',
          success: (res) => {
            // console.log(res.data)
        })
      },
    

    相关文章

      网友评论

          本文标题:小程序 http封装

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