返回
顶部

修改密码

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

+1

-1

收藏

+1

-1

点赞0

评论0

httpExt.jsconst app = getApp()const util = require('/util.js')/*** wx.request的封装* 使用方式: httpExt.get("admin/login", {}).then(res => {}).catch(err => {})* @param {*} url 请求地址* @param {*} method 请求类型* @param {*} data 请求参数* @param {*} opt…

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 = {}, options = {}) => { return request(url, 'GET', data, options) } const post = (url, data = {}, 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 }) }); 复制代码

扫一扫在手机打开

评论
已有0条评论
0/150
提交
热门评论
相关推荐
微信小程序开发中常见的设计败笔
  • 开发资料
  • 2022-05-20 18:35
  • 14 0 0
+1
从王者荣耀里我学会的前端新手指引
  • 开发资料
  • 2022-05-20 18:35
  • 47 0 0
+1
微信小程序登录鉴权与获取用户信息
  • 开发资料
  • 2022-05-20 18:35
  • 4 0 0
+1
小程序录音功能实现
  • 开发资料
  • 2022-05-20 18:35
  • 26 0 0
+1
今日要闻
换一批
热点排行