微信小程序-wx.request的封装实现 - 新闻资讯 - 云南小程序开发|云南软件开发|云南网站建设-昆明葵宇信息科技有限公司

159-8711-8523

云南网建设/小程序开发/软件开发

知识

不管是网站,软件还是小程序,都要直接或间接能为您产生价值,我们在追求其视觉表现的同时,更侧重于功能的便捷,营销的便利,运营的高效,让网站成为营销工具,让软件能切实提升企业内部管理水平和效率。优秀的程序为后期升级提供便捷的支持!

您当前位置>首页 » 新闻资讯 » 小程序相关 >

微信小程序-wx.request的封装实现

发表时间:2021-2-28

发布人:葵宇科技

浏览次数:49

httpExt.js

const app = getApp() const util = require('/util.js') /** * wx.request的封装 * 使用方式: httpExt.get("admin/login", {}).then(res => {}).catch(err => {}) * @param {*} url 请求地址 * @param {*} method 请求类型 * @param {*} data 请求参数 * @param {*} options 接口配置 */ const request = (url, method, data, options) => { wx.showLoading({ title: '加载中', mask: true }) return new Promise((resolve, reject) => { wx.request({ url: util.getUrl(url), method: method || 'GET', data: method === 'GET' ? options.data : JSON.stringify(options.data), header: { 'Content-Type': 'application/json; charset=UTF-8', // 'token': wx.getStorageSync("SSP_token") }, success(res) { if (res.data.success == true) { resolve(res) } else { reject(res) } }, fail(error) { reject(error) }, complete: info => { wx.hideLoading() } }) }) } const get = (url, data = http://www.wxapp-union.com/{}, options = {}) => { return request(url, 'GET', data, options) } const post = (url, data = http://www.wxapp-union.com/{}, options = {}) => { return request(url, 'POST', data, options) } module.exports = { get, post } 复制代码

util.js

const hosts = require("/hosts.js") const formatTime = date => { const year = date.getFullYear() const month = date.getMonth() + 1 const day = date.getDate() const hour = date.getHours() const minute = date.getMinutes() const second = date.getSeconds() return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}` } const formatNumber = n => { n = n.toString() return n[1] ? n : `0${n}` } const getUrl = (url) => { if (url.indexOf('://') == -1) { url = hosts.actualHost.mainHostName + url; } return url } module.exports = { getUrl, formatTime } 复制代码

hosts.js

// pro 生产环境 sit 测试环境 (上线前需要修改为'pro') const hostType = 'sit' const version = '1.0' const host = { /** * 主服务域名 */ mainHostName: new Map([ ['pro', 'xxxxx'], ['sit', 'xxxxxx'] ]) } const actualHost = { mainHostName: host.mainHostName.get(hostType) } export { actualHost, hostType, version } 复制代码

使用:

const httpExt = require('../../utils/httpExt.js') httpExt.get("xxxx", {}).then(res => { // 接口成功操作 }).catch(err => { console.log("error:", err);/* */ // 接口失败操作 wx.showToast({ title: err.data.msg||"服务异常,请稍后重试!", icon: 'error', duration: 2000 }) }); 复制代码

相关案例查看更多