最近在進行小程序的編寫,需要調用后端接口,經常要用到wx.request方法,所以就自己封裝了一下,簡化一下代碼
1、app.js 創建全局數據
App({ // 全局數據
globalUrl:{ url:"http://localhost:8081/demo/"
}
})
2、方法封裝(新建文件夾util,工具文件,在文件夾下創建utils.js文件,用於對方法封裝;請求地址提取出來使用app.js中的url)
utils.js
// 全局request封裝 /** * config:{ * url:'', * method:'', * data:"" * } */ /** * 請求方式可傳,不傳為GET * postData:參數,json類型 * callback:成功的回調函數 * errorCallBack:失敗的回調函數 */ const APP = getApp(); //項目URL相同部分,減輕代碼量,同時方便項目遷移 const REQUESTURL = APP.globalUrl.url; function request(config, callback, errorCallBack) { //請求接口時默認loading效果,黑色本框轉圈圈 wx.showLoading(); wx.request({ url: REQUESTURL+config.url, method:config.method?config.method:"GET", data:config.data?config.data:"", success(res){ if(res.data.code==200){ wx.hideLoading(); //隱藏loading //默認成功展示對號 if (callback) { wx.showToast({ title: res.data.msg, icon: 'none', duration: 2000 }) callback(res) } }else if(res.data.code==406){ //跳轉登錄 }else{ wx.hideLoading(); //隱藏loading if (errorCallBack) { errorCallBack(res) } else { wx.showToast({ title: res.data.msg, icon: 'none', duration: 2000 }) } } } }) } module.exports = { request: request }
3、請求封裝函數的引用,page里面創建一個文件夾index,創建四種文件,在js里面加入:
/** *引入getApp();是app.js中的全局數據URL *utils引入使用請求封裝函數 */ const APP = getApp(); var utils = require("../util/utils.js"); Page({ /** * 頁面的初始數據 */ data: { }, onLoad: function (options) { var that = this; var getVinUrl = "/survey/getVin/";
//ajax請求 utils.request({ url: getVinUrl, method: 'GET', data: this.data.phone }, function (res) { //請求成功
connsole.log(res); }, function (err) { //請求失敗
connsole.log(err); }); } })