网站建设资讯

​微信小程序request封装

网站制作 2018-11-29 10:22:06 | 阅读:1646
微信小程序request封装
Request的做小程序是必不可少的,所有后端网络请求都要用到request,虽然微信的request相对来说已经很简洁,但对http status code的判断,处理异常都不是很方便
首先新建一个request.js
 
class request {
  constructor() {
    this._header = {'content-type': 'application/x-www-form-urlencoded'}
  }
 
  /**
   * 设置统一的异常处理
   */
  setErrorHandler(handler) {
    this._errorHandler = handler;
  }
 
  /**
   * GET类型的网络请求
   */
  getRequest(url, data, header = this._header) {
    return this.requestAll(url, data, header, 'GET')
  }
 
  /**
   * DELETE类型的网络请求
   */
  deleteRequest(url, data, header = this._header) {
    return this.requestAll(url, data, header, 'DELETE')
  }
 
  /**
   * PUT类型的网络请求
   */
  putRequest(url, data, header = this._header) {
    return this.requestAll(url, data, header, 'PUT')
  }
 
  /**
   * POST类型的网络请求
   */
  postRequest(url, data, header = this._header) {
    return this.requestAll(url, data, header, 'POST')
  }
 
  /**
   * 网络请求
   */
  requestAll(url, data, header, method) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: url,
        data: data,
        header: header,
        method: method,
        success: (res => {
          if (res.statusCode === 200) {
            //200: 服务端业务处理正常结束
            resolve(res) 
            //请求返回401 跳转登陆          
            if(res.data.code=="401"){
              wx.reLaunch({
                url: '/pages/login/index',
              })
            }       
          } else {
            //其它错误,提示用户错误信息
            if (this._errorHandler != null) {
              //如果有统一的异常处理,就先调用统一异常处理函数对异常进行处理
              this._errorHandler(res)
            }
            reject(res)
          }
        }),
        fail: (res => {
          if (this._errorHandler != null) {
            this._errorHandler(res)
          }
          reject(res)
        })
      })
    })
  }
}
 
export default request
 
 
新建getApi.js
 
import request from './request.js'
import utilMd5 from './md5.js'
class getApi{
  constructor() {
    this._baseUrl = 'https:xxxx'
    this._defaultHeader = {
      'data-tupe': 'application/json'
    }
    this._request = new request
    this._request.setErrorHandler(this.errorHander)
    this._key = 'szfangwei_net'
  }
 
  /**
   * timestamp
   */
  timestamp() {
    //获取当前时间戳
    let timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    //获取当前时间
    let n = timestamp * 1000;
    let date = new Date(n);
    let Y = date.getFullYear(); //年   
    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1); //月   
    let D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(); //日   
    let h = date.getHours(); //时   
    let m = date.getMinutes(); //分   
    let s = date.getSeconds(); //秒
    return Y.toString() + M + D + h + m + s;
  }
 
  /**
   * 公共参数
   */
  connDate(data) {
    let timestamp = this.timestamp();
    let conn = {
      timestamp: timestamp,
      token: utilMd5.hexMD5(timestamp + this._key),
    }
    return Object.assign(conn, data);
  }
 
  /**
   * 统一的异常处理方法
   */
  errorHander(res) {
    console.error(res)
  }
 
 
 
  /**
   * 验证token
   */
  getToken(session3rd) {
    let url = "User/xxx"
    let data = {
      device_token: 'wechat',
      session3rd: session3rd
    }
    return this._request.getRequest(this._baseUrl + url, this.connDate(data)).then(res => res.data)
  }
 
 
 
 
 
 
  /**
   * 获取项目
   */
  getProject(session3rd, userID, cpage,k='') {
    let url = "Project/xx"
    let data = {
      session3rd: session3rd,
      userID: userID,
      cpage: cpage,
      k:k
    }
    return this._request.getRequest(this._baseUrl + url, this.connDate(data)).then(res => res.data)
  }
 
}
export default getApi
 
 
最后在app。Js实例化
Import getApi from ‘./apis/request.js’
getApi:new getApi()
 
 
在pages里使用
Const app = getApp();

getdataList() {
    app.getApi.getCourseList(this.data.xx)
      .then(res => {
       
        this.setData({
          list: list
        })
      })
      .catch(res => {
        //you code
      })
  },