微信小程序开发网络请求的简易封装支持async-await异步操作
目录
- 更多分享:www.catbro.cn
涉及知识点:
网络请求:
- 1、引入async-await异步请求能力,详情请看微信小程序 引入async 和await支持
- 2、对网络请求的简易封装
- 3、loading 提示窗的使用
封装代码如下:
-
封装了GET、PUT、DELETE、PUT等方法,可满足日常的使用
-
代码如下
const baseUrl = 'http://localhost:8080'; const http = ({ url = '', param = {}, method = 'GET'} = {}) => { wx.showLoading({ title: '请求中,请耐心等待..' }); let timeStart = Date.now(); return new Promise((resolve, reject) => { wx.request({ url: getUrl(url), data: param, method: method, 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) => { console.log(url) url = baseUrl + url; console.log(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: 'DELETE' }) } module.exports = { baseUrl, _get, _post, _put, _delete }
-
使用时便可直接使用
async login(e) { console.log('form发生了submit事件,携带数据为:', e.detail.value) let loginData = e.detail.value if (util.isNullOrEmpty(loginData.userName)) { wx.showToast({ title: "用户名不能为空" }) return } if (util.isNullOrEmpty(loginData.password)) { wx.showToast({ title: "密码不能为空" }) return } let result = await api._post('/api/user/login', loginData) console.log(result) if (result.code == -1) { wx.showModal({ title: '温馨提示', content: result.msg, showCancel: false }) return } //登录成功,存储用户信息 wx.setStorageSync('user', result.data) wx.switchTab({ url: '../index/index', }) wx.showToast({ title: '登录成功' }) },