国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

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

2019-11-19 13:25:43
字體:
供稿:網(wǎng)友

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

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

// 官方例子wx.request({ url: 'test.php', //僅為示例,并非真實的接口地址 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: '請求中,請耐心等待..'  });  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(`耗時${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)})

登陸問題

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

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

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

登陸

//app.jsApp({ 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去訪問我們的后臺換取其他信息    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】 如果成功后設(shè)置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 參數(shù),下面注冊接口需要用到    wx.getUserInfo({     success: function (res) {      var iv = res.iv;      var encryptedData = res.encryptedData;      // 下面開始調(diào)用注冊接口      wx.request({       url: 'https://api.it120.cc/' + that.globalData.subDomain +'/user/wxapp/register/complex',       data: {code:code,encryptedData:encryptedData,iv:iv}, // 設(shè)置請求的 參數(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接口不會彈窗詢問       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ò)請求這塊,算目前開發(fā)項目中必不可少的一塊加油~~

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 江华| 大悟县| 锡林郭勒盟| 保山市| 玉溪市| 仁化县| 正蓝旗| 和田县| 华亭县| 扶风县| 太保市| 佛冈县| 正阳县| 东至县| 鹰潭市| 乌兰县| 攀枝花市| 田东县| 墨玉县| 翼城县| 北碚区| 三原县| 蓬安县| 西安市| 万州区| 南昌县| 莱阳市| 宿州市| 蓬莱市| 屏边| 玉溪市| 兴隆县| 安阳县| 惠东县| 汉沽区| 宿松县| 阿拉善右旗| 钦州市| 兰考县| 阿图什市| 宜都市|