微信小程序 wxRequest封装

前端之家收集整理的这篇文章主要介绍了微信小程序 wxRequest封装前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
/Api/myRequest.js

const baseUrl = 'https://api.it120.cc';

const http = ({ url = '',param = {},...other } = {}) => {
wx.showLoading({
title: '请求中...'
});
let timeStart = Date.now();
return new Promise((resolve,reject) => {
wx.request({
url: url,data: param,header: {
"content-type": "application/x-www-form-urlencoded" // 默认值,另一种是 "content-type": "application/x-www-form-urlencoded"
},...other,complete: (res) => {
wx.hideLoading();
console.log(耗时${Date.now() - timeStart});
},success: (res) => {
resolve(res.data)
},fail: () => {
reject(res)
}
})
})
}

const getUrl = (url) => {
if (url.indexOf('://') == -1) {
url = baseUrl + url;
}
return url
}

// get方法
const _get = (url,param = {}) => {
return http({
url,param
})
}

const _post = (url,param,method: 'post'
})
}

const _put = (url,method: 'put'
})
}

const _delete = (url,method: 'put'
})
}
module.exports = {
baseUrl,_get,_post,_put,_delete
}

// Api/api.js

import api from './myRequest.js';
const baseUrl = 'https://api.it120.cc';

function getList(data) {
let url = baseUrl + '/34vu54u7vuiuvc546d' + '/banner/list';
return api._post(url,data)
}

module.exports = {
getList
}

// app.js 使用
//app.js
import api from '/Api/api.js';
App({
  onLaunch: function () {
    // 
    api.getList({ key: 'mallName'}).then(function(res) {
      console.log(res);
    })
  }
})

猜你在找的微信小程序相关文章