小程序_请求封装network
时间:2018-10-22 14:52:14
收藏:0
阅读:206
在utils目录下创建network.js文件封装请求
封装的network.js:
1 //模块一,全局变量 2 let urlList = { 3 host: ‘http://47.106.25.53/‘, 4 loginHost: "http://47.106.25.53/", 5 webModelUrl: ‘ipp-web/‘, //登陆模块 6 mobileModelUrl: ‘ipp-mobile/‘, //业务模块 7 authModelUrl: ‘ipp-auth-web/‘, //上传图片 8 }, 9 requestHandler = { 10 title: ‘‘, 11 url: ‘‘, 12 success: function (res) { 13 14 }, 15 fail: function () { 16 17 } 18 }, 19 domain = urlList.host + urlList.mobileModelUrl; 20 //--------end------------ 21 22 //模块二,处理请求 23 function request(method, requestHandler) { 24 const token = wx.getStorageSync(‘token‘); 25 if (!requestHandler.title) requestHandler.title = "加载中"; 26 wx.showLoading({ 27 title: requestHandler.title, 28 }) 29 setTimeout(function () { 30 wx.hideLoading() 31 }, 10000); 32 wx.request({ 33 url: domain + requestHandler.url, 34 data: requestHandler.data, 35 method: method, 36 header: { 37 "X-Requested-With": "XMLHttpRequest", 38 ‘Content-Type‘: ‘application/json‘, 39 ‘token‘: token 40 }, 41 dataType: ‘json‘, 42 success: function (res) { 43 if (res.data.msgCode == ‘F0006‘ || res.data.msgCode == ‘F0007‘) { 44 /*wx.showModal({ 45 title: ‘温馨提示‘, 46 content: ‘登录已失效,请重新登录!‘, 47 cancelText: ‘取消‘, 48 confirmText: ‘确定‘, 49 success: function (res) { 50 wx.reLaunch({ 51 url: ‘../logs/logs‘, 52 }) 53 } 54 })*/ 55 } 56 wx.hideLoading() 57 requestHandler.success(res) 58 }, 59 fail: function () { 60 wx.hideLoading() 61 requestHandler.fail() 62 } 63 }) 64 } 65 //---------end----------- 66 67 68 //模块三,请求方法 69 //GET请求 70 function GET(requestHandler) { 71 request(‘GET‘, requestHandler) 72 }; 73 //POST请求 74 function POST(requestHandler) { 75 request(‘POST‘, requestHandler) 76 }; 77 //--------end----------- 78 79 80 81 //模块四,输出方法 82 module.exports = { 83 GET: GET, 84 POST: POST, 85 urlList: urlList 86 }; 87 //-----end----------
在页面上使用require引入输出的封装对象:
1 const network = require(‘../../utils/network.js‘);
使用方法:
1 network.POST({ 2 url: ‘asnorder/getPackingUnitInfo.shtml‘, 3 data: {}, 4 success: function (res) { 5 6 }, 7 })
评论(0)