微信小程序網絡請求封裝

網絡請求

網絡請求小程序提供了wx.request, 仔細看一下 api,這不就是n年前的 $.ajax 嗎,好古老啊。javascript

// 官方例子
wx.request({
  url: 'test.php', //僅爲示例,並不是真實的接口地址
  data: {
     x: '' ,
     y: ''
  },
  header: {
      'content-type': 'application/json' // 默認值
  },
  success: function(res) {
    console.log(res.data)
  }
})

小程序支持ES6,那麼就應該支持Promise 了,很開心~, 話很少說直接上代碼吧php


Promise封裝
const baseUrl = 'https://api.it120.cc';

const http = ({ url = '', param = {}, ...other } = {}) => {
    wx.showLoading({
        title: '請求中,請耐心等待..'
    });
    let timeStart = Date.now();
    return new Promise((resolve, reject) => {
        wx.request({
            url: getUrl(url),
            data: param,
            header: {
                'content-type': 'application/json' // 默認值 ,另外一種是 "content-type": "application/x-www-form-urlencoded"
            },
            ...other,
            complete: (res) => {
                wx.hideLoading();
                console.log(`耗時${Date.now() - timeStart}`);
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    resolve(res.data)
                } else {
                    reject(res)
                }
            }
        })
    })
}

const getUrl = (url) => {
    if (url.indexOf('://') == -1) {
        url = baseUrl + url;
    }
    return url
}

// get方法
const _get = (url, param = {}) => {
    return http({
        url,
        param
    })
}

const _post = (url, param = {}) => {
    return http({
        url,
        param,
        method: 'post'
    })
}

const _put = (url, param = {}) => {
    return http({
        url,
        param,
        method: 'put'
    })
}

const _delete = (url, param = {}) => {
    return http({
        url,
        param,
        method: 'put'
    })
}
module.exports = {
    baseUrl,
    _get,
    _post,
    _put,
    _delete
}
使用
const api = require('../../utils/api.js')

// 單個請求
api.get('list').then(res => {
  console.log(res)
}).catch(e => {
  console.log(e)
})

// 一個頁面多個請求
Promise.all([
  api.get('list'),
  api.get(`detail/${id}`)
]).then(result => {
  console.log(result)
}).catch(e => {
  console.log(e)
})

登錄問題java

作一個應用,確定避免不了登陸操做。用戶的我的信息啊,相關的收藏列表等功能都須要用戶登陸以後才能操做。通常咱們使用token作標識。ajax

小程序並無登陸界面,使用的是 wx.login wx.login 會獲取到一個 code,拿着該 code 去請求咱們的後臺會最後返回一個 token到小程序這邊,保存這個值爲 token 每次請求的時候帶上這個值。

通常還須要把用戶的信息帶上好比用戶微信暱稱,微信頭像等,這時候就須要使用 wx.getUserInfo ,這裏涉及到一個用戶受權的問題json

帶上用戶信息就夠了嘛? too young too simple!咱們的項目不可能只有小程序,相應的微信公衆平臺可能還有相應的App,咱們須要把帳號系統打通,讓用戶在咱們的項目中的帳戶是同一個。這就須要用到微信開放平臺提供的 UnionID 。小程序

登錄api

//app.js
App({
  onLaunch: function () {
    console.log('App onLaunch');
    var that = this;
    //  獲取商城名稱
    wx.request({
      url: 'https://api.it120.cc/'+ that.globalData.subDomain +'/config/get-value',
      data: {
        key: 'mallName'
      },
      success: function(res) {
        wx.setStorageSync('mallName', res.data.data.value);
      }
    })
    this.login();
    this.getUserInfo();
  },
  login : function () {
    var that = this;
    var token = that.globalData.token;
    // 若是有token
    if (token) {
      // 檢查token是否有效
      wx.request({
        url: 'https://api.it120.cc/' + that.globalData.subDomain + '/user/check-token',
        data: {
          token: token
        },
        success: function (res) {
          // 若是token失效了
          if (res.data.code != 0) {
            that.globalData.token = null;
            that.login(); // 從新登錄
          }
        }
      })
      return;
    }

    // 【1】調用微信自帶登錄
    wx.login({
      success: function (res) {
        // 【2】 拿到code去訪問咱們的後臺換取其餘信息
        wx.request({
          url: 'https://api.it120.cc/'+ that.globalData.subDomain +'/user/wxapp/login',
          data: {
            code: res.code
          },
          success: function(res) {
            // 若是說這個code失效的
            if (res.data.code == 10000) {
              // 去註冊
              that.registerUser();
              return;
            }
            // 若是返回失敗了
            if (res.data.code != 0) {
              // 登陸錯誤 
              wx.hideLoading();
              // 提示沒法登錄
              wx.showModal({
                title: '提示',
                content: '沒法登陸,請重試',
                showCancel:false
              })
              return;
            }
            
            // 【3】 若是成功後設置token到本地
            that.globalData.token = res.data.data.token;
            // 保存用戶信息
            wx.setStorage({
              key: 'token',
              data:  res.data.data.token
            })
          }
        })
      }
    })
  },
  // 註冊?? [這個看需求]
  registerUser: function () {
    var that = this;
    wx.login({
      success: function (res) {
        var code = res.code; // 微信登陸接口返回的 code 參數,下面註冊接口須要用到
        wx.getUserInfo({
          success: function (res) {
            var iv = res.iv;
            var encryptedData = res.encryptedData;
            // 下面開始調用註冊接口
            wx.request({
              url: 'https://api.it120.cc/' + that.globalData.subDomain +'/user/wxapp/register/complex',
              data: {code:code,encryptedData:encryptedData,iv:iv}, // 設置請求的 參數
              success: (res) =>{
                wx.hideLoading();
                that.login();
              }
            })
          }
        })
      }
    })
  },
  // 獲取用戶信息
  getUserInfo:function() {
    wx.getUserInfo({
      success:(data) =>{
        this.globalData.userInfo = data.userInfo;
        wx.setStorage({
          key: 'userInfo',
          data:  data.userInfo
        })
        return this.globalData.userInfo;
      }
    })
  },
  globalData:{
    userInfo:null,
    subDomain:"34vu54u7vuiuvc546d",
    token: null
  }
})

受權問題微信

getUserInfo: function () {
    // 先調用wx.getSetting 獲取用戶權限設置
    wx.getSetting({
      success(res) {
        console.log('1');
        if (!res.authSetting['scope.userInfo']) {
          wx.authorize({
            scope: 'scope.userInfo',
            success() {
              // 用戶已經贊成小程序使用錄音功能,後續調用 wx.getUserInfo接口不會彈窗詢問
              wx.getUserInfo({
                success: (data) => {
                  this.globalData.userInfo = data.userInfo;
                  wx.setStorage({
                    key: 'userInfo',
                    data: data.userInfo
                  })
                  return this.globalData.userInfo;
                }
              })
            }
          })
        } else {
          console.log(2);
        }
      }
    })

  },

小結網絡

網絡請求這塊,算目前開發項目中必不可少的一塊加油~~app

相關文章
相關標籤/搜索