小程序模板網(wǎng)

微信小程序Http高級封裝 es6 promise

發(fā)布時間:2018-04-25 10:33 所屬欄目:小程序開發(fā)教程

公司突然要開放微信小程序,持續(xù)蒙蔽的我還不知道小程序是個什么玩意。

于是上網(wǎng)查了一下,就開始著手開發(fā)。。。。。

首先開發(fā)客戶端的東西,都有個共同點,那就是 數(shù)據(jù)請求!

看了下小程序的請求方式大概和ajax請求差不多,所以先打好基礎 從封裝http請求開始

好了廢話不多說了,上代碼

首先。。。。當然是建立配置文件,用來配置請求根路徑

config.js

export default {
  basePath: 'http://192.168.6.2:9002/api',
  fileBasePath: 'http://192.168.6.2:9002',
  //basePath: 'http://127.0.0.1:8989/api',
  //fileBasePath: 'http://127.0.0.1:8989',
  defaultImgUrl:'/pages/Images/default.png'
}

這里我用到es6來寫邏輯代碼 所以自行引用兼容代碼es6-promise.js

下面是核心代碼

ServiceBase.js

import __config from '../etc/config'
import es6 from '../assets/plugins/es6-promise'

class ServiceBase {
  constructor() {
    Object.assign(this, {
      $$basePath: __config.basePath
    })
    this.__init()
  }

  /**
   * __init
   */
  __init() {
    this.__initDefaults()
    this.__initMethods()
  }

  /**
   * __initDefaults
   */
  __initDefaults() {
    // 方法名后綴字符串
    this.suffix = 'Request'

    // 發(fā)起請求所支持的方法
    this.instanceSource = {
      method: [
        'OPTIONS',
        'GET',
        'HEAD',
        'POST',
        'PUT',
        'DELETE',
        'TRACE',
        'CONNECT',
      ]
    }
  }

  /**
   * 遍歷對象構造方法,方法名以小寫字母+后綴名
   */
  __initMethods() {
    for (let key in this.instanceSource) {
      this.instanceSource[key].forEach((method, index) => {
        this[method.toLowerCase() + this.suffix] = (...args) => this.__defaultRequest(method, ...args)
      })
    }
  }

  /**
   * 以wx.request作為底層方法
   * @param {String} method 請求方法
   * @param {String} url    接口地址
   * @param {Object} params 請求參數(shù)
   * @param {Object} header 設置請求的 header
   * @param {String} dataType 請求的數(shù)據(jù)類型
   */
  __defaultRequest(method = '', url = '', params = {}, header = {}, dataType = 'json') {
    const $$header = Object.assign({}, this.setHeaders(), header)
    const $$url = this.setUrl(url)

    // 注入攔截器
    const chainInterceptors = (promise, interceptors) => {
      for (let i = 0, ii = interceptors.length; i < ii;) {
        let thenFn = interceptors[i++]
        let rejectFn = interceptors[i++]
        promise = promise.then(thenFn, rejectFn)
      }
      return promise
    }
    //加入token信息
    params.AccessToken = wx.getStorageSync('token');
    params.Version = wx.getStorageSync('Version')||"20151101";
    // 請求參數(shù)配置
    const $$config = {
      url: $$url,
      data: params,
      header: $$header,
      method: method,
      dataType: dataType,
    }

    let requestInterceptors = []
    let responseInterceptors = []
    let reversedInterceptors = this.setInterceptors()
    let promise = this.__resolve($$config)

    // 緩存攔截器
    reversedInterceptors.forEach((n, i) => {
      if (n.request || n.requestError) {
        requestInterceptors.push(n.request, n.requestError)
      }
      if (n.response || n.responseError) {
        responseInterceptors.unshift(n.response, n.responseError)
      }
    })

    // 注入請求攔截器
    promise = chainInterceptors(promise, requestInterceptors)

    // 發(fā)起HTTPS請求
    promise = promise.then(this.__http)

    // 注入響應攔截器
    promise = chainInterceptors(promise, responseInterceptors)

    // 接口調用成功,res = {data: '開發(fā)者服務器返回的內容'}
    promise = promise.then(res => res.data, err => err)

    return promise
  }

  /**
   * __http - wx.request
   */
  __http(obj) {
    return new es6.Promise((resolve, reject) => {
      obj.success = (res) => resolve(res)
      obj.fail = (res) => reject(res)
      wx.request(obj)
    })
  }

  /**
   * __resolve
   */
  __resolve(res) {
    return new es6.Promise((resolve, reject) => {
      resolve(res)
    })
  }

  /**
   * __reject
   */
  __reject(res) {
    return new es6.Promise((resolve, reject) => {
      reject(res)
    })
  }

  /**
   * 設置請求路徑
   */
  setUrl(url) {
    return `${this.$$basePath}${this.$$prefix}${url}`
  }

  /**
   * 設置請求的 header , header 中不能設置 Referer
   */
  setHeaders() {
    return {
      // 'Accept': 'application/json', 
      // 'Content-type': 'application/json', 
      "Content-Type": "application/x-www-form-urlencoded" 
      //'Authorization': 'Bearer ' + wx.getStorageSync('token')
    }
  }

  /**
   * 設置request攔截器
   */
  setInterceptors() {
    return [{
      request: (request) => {
        request.header = request.header || {}
        request.requestTimestamp = new Date().getTime()
    
       //如果token在header中 token在參數(shù)中注入if (request.url.indexOf('/api') !== -1 && wx.getStorageSync('token')) {
          //request.header.Authorization = 'T ' + wx.getStorageSync('token')  }
        wx.showToast({
          title: '加載中',
          icon: 'loading',
          duration: 10000,
          mask: !0,
        })
        return request
      },
      requestError: (requestError) => {
        wx.hideToast()
        console.log('error-------------');
        return requestError
      },
      response: (response) => {
        console.log(response)
        response.responseTimestamp = new Date().getTime()
        if (response.statusCode == 401 
        || response.statusCode == 403
          || (response.data.code == -1 && response.data.tips =="云客戶端連接失敗"))
        {
          wx.removeStorageSync('token')
          wx.removeStorageSync('userinfo')
          wx.redirectTo({
            url: '/pages/login/login?isfail=true'
          })
        }
        wx.hideToast()
        return response
      },
      responseError: (responseError) => {
        wx.hideToast()
        return responseError
      },
    }]
  }
}

export default ServiceBase

下面是業(yè)務邏輯的DAO層

import ServiceBase from 'ServiceBase'

class Service extends ServiceBase {
  constructor() {
    super()
    this.$$prefix = ''
    this.$$path = {
      register:'/login/weregister',//注冊
      signIn : '/login/login',//登陸
      wechatSignIn: '/login/welogin',//微信登陸
      signOut: '/login/logout',//退出

    }
  }
  //openid和基本信息注冊
  register(params)
  {
    return this.postRequest(this.$$path.register, params) 
  }
  //用戶名密碼登陸
  signIn(params) {
    return this.postRequest(this.$$path.signIn, params)
  }
  //微信登陸
  wechatSignIn(params) {
    return this.postRequest(this.$$path.wechatSignIn, params)
  }
  signOut() {
    return this.postRequest(this.$$path.signOut)
  }


}

export default Service

有人可能會問 如何進行get請求?

this.postRequest 換成 this.getRequest 即可 其他put,delete 類似 然后在全局app.js 進行引用

import HttpService from 'Core/HttpService'

App({

...

...

HttpService: new HttpService

})

最后調用方式

    signIn(cb) {
  //測試默認登陸成功
    app.HttpService.signIn({
      username: '571115139',
      password: '666666',
    })
      .then(data => {
    //請求成功
        console.log(data)

        //測試數(shù)據(jù) 

        cb()

      }).catch(e=>{
    //請求失敗
    })

  }

好了今天就說到這,下篇將持續(xù)更新在小程序中遇到的坑


易優(yōu)小程序(企業(yè)版)+靈活api+前后代碼開源 碼云倉庫:starfork
本文地址:http://22321a.com/wxmini/doc/course/24030.html 復制鏈接 如需定制請聯(lián)系易優(yōu)客服咨詢:800182392 點擊咨詢
QQ在線咨詢