小程序api請求工具類封裝(uni-app開箱即用)

api工具類(utils/http.js)

const appId = 'wxbdb4d63f81d98228' //此處爲appId
class HTTP {
  constructor() {
    this.baseUrl = 'https://www.baidu.com'
  }

  request({
    url,
    data = {},
    method = 'GET'
  }){
      return new Promise((resolve, reject) => {
        this._request(url, resolve, reject, data, method)
      })
    }

  _request(url, resolve, reject, data = {}, method = 'GET') {
    uni.request({
      url: url,
      method: method,
      data: data,
      header: {
        'content-type': 'application/json',
        'appId': appId,
        'token': uni.getStorageSync('AUTH_TOKEN')
      },
      success: (res) => {
        if (res.data) {
            const _success = res.data.success;
            if (_success) {
              resolve(res.data)
            } else {
              reject(res.data.message)
              this._show_error(res.data.message)
            }
        } else {
            resolve(res.data)
        }
      },
      fail: (err) => {
          reject()
          this._show_error(err.data.message)
      }
    })
  }

  _show_error(_message) {
    uni.showToast({
      title: `${_message}`,
      icon: 'none',
      duration: 2000
    })
  }
}

export {
	HTTP
}
複製代碼

model層獲取數據(models/app.js)

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

class AppModel extends HTTP {
  login(params) {
    return this.request({
      url: `${this.baseUrl}/api/login`,
      method: 'POST',
      data: {
        ...params
      }
    })
  }
}

export { AppModel }
複製代碼

調用

import { AppModel } from 'models/app.js'
const appModel = new AppModel()
appModel.login(params)
  .then(response => {
    uni.showLoading({
      title: '加載中'
    })
    setTimeout(() => {
      uni.hideLoading();
    })
  })
  .catch(errors => {
    uni.hideLoading();
  })
複製代碼
相關文章
相關標籤/搜索