小程序wx.request请求封装

xiaoxiao2021-02-27  430

关于小程序的请求封装,我们使用promise可以更加方便快捷的实现。

service.js function request(url,data){ return new Promise(function(reslove,reject){ //网络请求 wx.request({ url: url, data: data, method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT header: { 'Content-Type': 'application/x-www-form-urlencoded' }, // 设置请求的 header success: function(res){ // success网络请求成功 if(res.statusCode!=200){ reject({error:'服务器忙,请稍后重试',code:500}); return; } resolve(res.data.data); }, fail: function(res) { // fail调用接口失败 reject({error:'网络错误',code:0}); }, complete: function(res) { // complete } }) }) } //接口调用 module.expors={ //登录 login:function(mobile,password){ return requset(url,{mobile:mobile,password:password}); } }

这样我们就可以轻松实现网络请求的封装与调用

转载请注明原文地址: https://www.6miu.com/read-1770.html

最新回复(0)