小程序http封装

6次阅读

共计 1146 个字符,预计需要花费 3 分钟才能阅读完成。

import {config} from '../config.js' 
// 导入 config.js 中的接口链接
const tips = {
  1:"抱歉,出现了一个错误,请联系开发人员",
  1005:"接口、appey 错误",
  1006:"服务器内部错误",
  1004:"禁止访问"
}
class HTTP {constructor() {this.baseRestUrl = config.api_blink_url}

  //http 请求类, 当 noRefech 为 true 时,不做未授权重试机制
  request(params) {
    var that = this;
    var url = this.baseRestUrl + params.url;

    if (!params.method) {params.method = 'GET';}
    wx.request({
      url: url,
      data: params.data,
      method: params.method,
      header: {
        'content-type': 'application/json',
        'appkey': config.appkey
      },
      success: function (res) {// 判断以 2(2xx) 开头的状态码为正确
        // 异常不要返回到回调中,就在 request 中处理,记录日志并 showToast 一个统一的错误即可
        var code = res.statusCode.toString();
        console.log(res)
        // es5 写法
        // var startChar = code.charAt(0);
        // if (startChar == '2') {//   params.success && params.success(res.data);
        // } else {//   params.error && params.error(res);
        // }

        // es6 写法
        if (code.startsWith("2")) {params.success && params.success(res.data);
        } else {// params.error && params.error(res);
          let error_code = res.data.error_code;
          console.log(error_code)
          that.show_error(error_code)
        }
      },
      fail: function (err) {// params.fail && params.fail(err)
        this.show_error(1)
      }
    });
  }
  show_error(error_code) {if(!error_code){error_code = 1}
    wx.showToast({title: tips[error_code],
      icon: 'none',
      duration: 2000
    })
  }
}

export {HTTP};

正文完
 0