欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

微信小程序網(wǎng)絡(luò)請(qǐng)求封裝示例

 更新時(shí)間:2018年07月24日 11:33:54   作者:Meils  
這篇文章主要介紹了微信小程序網(wǎng)絡(luò)請(qǐng)求封裝示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

網(wǎng)絡(luò)請(qǐng)求

網(wǎng)絡(luò)請(qǐng)求小程序提供了wx.request, 仔細(xì)看一下 api,這不就是n年前的 $.ajax 嗎,好古老啊。

// 官方例子
wx.request({
 url: 'test.php', //僅為示例,并非真實(shí)的接口地址
 data: {
   x: '' ,
   y: ''
 },
 header: {
   'content-type': 'application/json' // 默認(rèn)值
 },
 success: function(res) {
  console.log(res.data)
 }
})

小程序支持ES6,那么就應(yīng)該支持Promise 了,很開心~, 話不多說直接上代碼吧

Promise封裝

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

const http = ({ url = '', param = {}, ...other } = {}) => {
  wx.showLoading({
    title: '請(qǐng)求中,請(qǐng)耐心等待..'
  });
  let timeStart = Date.now();
  return new Promise((resolve, reject) => {
    wx.request({
      url: getUrl(url),
      data: param,
      header: {
        'content-type': 'application/json' // 默認(rèn)值 ,另一種是 "content-type": "application/x-www-form-urlencoded"
      },
      ...other,
      complete: (res) => {
        wx.hideLoading();
        console.log(`耗時(shí)${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')

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

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

登陸問題

做一個(gè)應(yīng)用,肯定避免不了登錄操作。用戶的個(gè)人信息啊,相關(guān)的收藏列表等功能都需要用戶登錄之后才能操作。一般我們使用token做標(biāo)識(shí)。

小程序并沒有登錄界面,使用的是 wx.login 。 wx.login 會(huì)獲取到一個(gè) code,拿著該 code 去請(qǐng)求我們的后臺(tái)會(huì)最后返回一個(gè)token到小程序這邊,保存這個(gè)值為 token 每次請(qǐng)求的時(shí)候帶上這個(gè)值。
一般還需要把用戶的信息帶上比如用戶微信昵稱,微信頭像等,這時(shí)候就需要使用 wx.getUserInfo ,這里涉及到一個(gè)用戶授權(quán)的問題

帶上用戶信息就夠了嘛? too young too simple!我們的項(xiàng)目不可能只有小程序,相應(yīng)的微信公眾平臺(tái)可能還有相應(yīng)的App,我們需要把賬號(hào)系統(tǒng)打通,讓用戶在我們的項(xiàng)目中的賬戶是同一個(gè)。這就需要用到微信開放平臺(tái)提供的 UnionID 。

登陸

//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】調(diào)用微信自帶登陸
  wx.login({
   success: function (res) {
    // 【2】 拿到code去訪問我們的后臺(tái)換取其他信息
    wx.request({
     url: 'https://api.it120.cc/'+ that.globalData.subDomain +'/user/wxapp/login',
     data: {
      code: res.code
     },
     success: function(res) {
      // 如果說這個(gè)code失效的
      if (res.data.code == 10000) {
       // 去注冊(cè)
       that.registerUser();
       return;
      }
      // 如果返回失敗了
      if (res.data.code != 0) {
       // 登錄錯(cuò)誤 
       wx.hideLoading();
       // 提示無法登陸
       wx.showModal({
        title: '提示',
        content: '無法登錄,請(qǐng)重試',
        showCancel:false
       })
       return;
      }
      
      // 【3】 如果成功后設(shè)置token到本地
      that.globalData.token = res.data.data.token;
      // 保存用戶信息
      wx.setStorage({
       key: 'token',
       data: res.data.data.token
      })
     }
    })
   }
  })
 },
 // 注冊(cè)?? [這個(gè)看需求]
 registerUser: function () {
  var that = this;
  wx.login({
   success: function (res) {
    var code = res.code; // 微信登錄接口返回的 code 參數(shù),下面注冊(cè)接口需要用到
    wx.getUserInfo({
     success: function (res) {
      var iv = res.iv;
      var encryptedData = res.encryptedData;
      // 下面開始調(diào)用注冊(cè)接口
      wx.request({
       url: 'https://api.it120.cc/' + that.globalData.subDomain +'/user/wxapp/register/complex',
       data: {code:code,encryptedData:encryptedData,iv:iv}, // 設(shè)置請(qǐng)求的 參數(shù)
       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
 }
})

授權(quán)問題

 getUserInfo: function () {
  // 先調(diào)用wx.getSetting 獲取用戶權(quán)限設(shè)置
  wx.getSetting({
   success(res) {
    console.log('1');
    if (!res.authSetting['scope.userInfo']) {
     wx.authorize({
      scope: 'scope.userInfo',
      success() {
       // 用戶已經(jīng)同意小程序使用錄音功能,后續(xù)調(diào)用 wx.getUserInfo接口不會(huì)彈窗詢問
       wx.getUserInfo({
        success: (data) => {
         this.globalData.userInfo = data.userInfo;
         wx.setStorage({
          key: 'userInfo',
          data: data.userInfo
         })
         return this.globalData.userInfo;
        }
       })
      }
     })
    } else {
     console.log(2);
    }
   }
  })

 },

小結(jié)

網(wǎng)絡(luò)請(qǐng)求這塊,算目前開發(fā)項(xiàng)目中必不可少的一塊加油~~

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論