再次封装uni.request
再次封装uni.request
看别人的uniapp代码时发现的,觉得蛮好用,自己试着用了下。。还行。。下面是代码:
//common/lib/request.js //接口返回固定有code,msg,data, 其中code=0为成功 export default { //全局配置 common: { baseUrl: 'http://localhost:5049/api', header: { 'Content-type' : 'application/json;chatset=UTF-8' }, data: {}, method: 'GET', dataType: 'json' }, //请求 返回 promise request(options = {}) { //组织参数 options.url = this.common.baseUrl + options.url options.header = options.header || this.common.header options.data = options.data || this.common.data options.method = options.method || this.common.method options.dataType = options.dataType || this.common.dataType console.log('进入request.js'); console.log('url:'+options.url); console.log('data:'+JSON.stringify(options.data)); console.log('method:'+options.method); //请求之前 uni.showLoading({ mask:true }) //请求中 return new Promise((res, rej) => { uni.request({ ...options, success: (result) => { //console.log('访问远程接口返回:'); //注意直接写console.log(result)是输出不了任何东西的 //console.log(JSON.stringify(result)); if (result.statusCode !== 200) { uni.showToast({ title: '服务器失败'+result.statusCode, mask: true, icon: 'none' }) return rej() } if (result.data.code!=0) { uni.showToast({ title: result.data.msg || '服务器失败', mask: true, icon: 'none' }) return; } let data = result.data.data res(data) }, fail: (error) => { console.log('接口访问失败'); uni.showToast({ title: error.errMsg || '请求失败', icon: 'none' }) return rej() }, complete: () => { uni.hideLoading() } }) }) }, //get请求 get(url, data = {}, options = {}) { options.url = url options.data = data options.method = 'GET' return this.request(options) }, //post请求 post(url, data = {}, options = {}) { options.url = url options.data = data options.method = 'POST' return this.request(options) }, //put请求 put(url, data = {}, options = {}) { options.url = url options.data = data options.method = 'PUT' return this.request(options) }, //delete请求 delete(url,data={},options={}){ options.url = url; options.data = data; options.method='DELETE'; return this.request(options); } }
使用:
//vue.js中的script <script> import $http from '@/common/lib/request.js' export default { data() { return { jifen:20, baseList: [] } }, onLoad() { this.GetData(); }, methods: { //读取接口数据 GetData(){ var u = uni.getStorageSync('userinfo'); $http.get('/qiandao/'+u.Id).then(res=>{ this.jifen = res.jifen; this.baseList = res.rili; }) }, //签到 QianDao(){ var u = uni.getStorageSync('userinfo'); $http.post('/qiandao/'+u.Id).then(res=>{ uni.showModal({ content:res.msg, showCancel:false }) }) } } } </script>
撸码:复制、粘贴,拿起键盘就是“干”!!!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具