1.在utils下新建 http.js

class HTTP {

  base_url = 'http://xxxx/' // 改成请求的地址

  get(url, data, config) {
    this._request({
      url,
      data,
      config,
      method: 'GET'
    })
  }

  post(url, data, config) {
    this._request({
      url,
      data,
      config,
      method: 'POST'
    })
  }

  static _isHttp(url) {
    return url.substr(0, 4).toLowerCase() === "http"
  }

  _request({ url, data, config, method }) {
    const token = my.getStorageSync({
      key: 'token', // 缓存数据的key
    }).data
    const is_http = HTTP._isHttp(url)
    // 未传入headers 
    let headers = {
      'content-type': 'application/json'
    }
    return new Promise((resolve, reject) => {
      my.request({
        headers: Object.assign(headers, {
          'X-Token': token || ''
        }),
        url: is_http ? url : this.base_url + url,
        data,
        method,
        ...config,
        success: (res) => {
          if (res.data.resultCode !== '200') {
            my.showToast({
              type: 'exception',
              content: res.data.message,
              duration: 2000
            });
          }
          resolve(res)
        },
        fail: (res) => {
          my.showToast({
            type: 'exception',
            content: '网络异常',
            duration: 2000
          });
          reject(res)
        }
      })
    })
  }
}

export { HTTP }

2.根目录新建一个文件夹modules,新建文件 modules/user.js,继承封装的http类

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

class UserModel extends HTTP {

  get_sms_code({
    appCode,
    mobile
  }) {
    console.log(this.x)
    return this.post('app_user/v1/get_sms_code', {
      appCode,
      mobile
    })
  }
}

export { UserModel }

3.页面中使用 如pages/login.js

import { UserModel } from '../../modules/user'
const userModel = new UserModel()

Page({

    onLoad(){
      this.get_sms_code()
    },

    async get_sms_code() {
      const res = await userModel.get_sms_code({
        appCode: '123456',
        mobile: '157xxx40150'
      })
     console.log(res)
  }

})
01-15 05:06