学习旧岛小程序 (4)封装api 请求

1.配置基本的 请求路径 和 key

config.js

const config = {
  baseUrl: 'http://bl.7yue.pro/v1/',
  appkey: ""
}
export { config }
//Es6的导出

2.封装

util/http

import { config } from '../config.js'


class HTTP {
  constructor() {
    this.baseRestUrl = config.baseUrl
  }
  //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();
        // var startChar = code.charAt(0);
        let  code  = res.statusCode.toString();
        if(code.startsWith('2')) {
          params.success && params.success(res.data);
        }else {
          params.error && params.error(res);
        }
        // if (startChar == '2') {
        //   params.success && params.success(res.data);
        // } else {
        //   params.error && params.error(res);
        // }
      },
      fail: function (err) {
        params.fail && params.fail(err)
      }
    });
  }
};

export { HTTP };

3.使用

先引入 ,再实例化

import  {HTTP} from   '../../utils/http.js'

  

let http = new  HTTP();

发送请求:

    // 单个请求
    http.request({
       url:'classic/latest',
       success: function(res) {
           console.log(res)
       }
    })
原文地址:https://www.cnblogs.com/guangzhou11/p/11283159.html