1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 微信小程序封装wx.request接口(两种方式)

微信小程序封装wx.request接口(两种方式)

时间:2018-09-12 23:01:41

相关推荐

微信小程序封装wx.request接口(两种方式)

方式一:在根目录新建一个api.js的文件用于存放wx.request的代码

api.js

const app = getApp();let postApi = function (apiUrl, data, successCallback, errorCallback, completeCallback){let apiData = {};if (data){apiData=data;}apiData.user_token=app.globalData.userToken;wx.request({url: app.rootUrl + apiUrl,method: "POST",data: apiData,success: res => {successCallback(res.data);},fail: err => {if (errorCallback){errorCallback(err);}else{wx.showToast({title: e,icon: 'none',duration: 1500,mask: false})}},complete: () => {if (completeCallback) {completeCallback();}}})}export default postApi;

注意:在app.js中定义rootUrl,rootUrl是接口url的公共部分 ,apiUrl是接口url的剩余部分

index.js中调用接口

const app = getApp();import postApi from "../../api.js";postApi("apiUrl?_tq=" + new Date().getTime(), data, res => {if (res.code == 0) {//请求成功执行}})

方式二:request.js文件

// export const API_URL = ''; // 项目域名/*** 网络请求封装 fetch*/export default function fetch(url, params, showLoading = true, method) {if (showLoading) {wx.showLoading({ title: '加载中' });}var cookie = wx.getStorageSync('cookie');if (!cookie) {cookie = '';}return new Promise((resolve, reject) => {wx.request({url: `${API_URL}${url}`,data: params || {},method: method || 'post',header: {"Accept": "*/*","Content-Type": "application/json; charset=UTF-8'","Cookie": cookie,},success: res => {resolve(res.data);},fail: error => {reject(error);},complete() {if (showLoading) {wx.hideLoading();}}})})}

在app.js文件引入该文件

在页面调用接口

在页面引入const app = getApp();

getWxUser(userD) {var params = {name:user.name,phone:userD.phone}app.fetch(接口地址, params).then(ret => {if (ret.status) {} else {wx.showModal({showCancel: false,content: ret.errmsg});}})},

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。