![](https://img.haomeiwen.com/i12175332/c1d2b784b44c3ba4.png)
JhHttpUtils.js 对 wx.request 进行封装 ,APICongfig.js对API进行管理,使用时可引用APICongfig 暴露出来的请求名,进行请求,便于维护。
demo 地址: https://github.com/iotjin/Jh_weapp
APICongfig 使用方法:
![](https://img.haomeiwen.com/i12175332/7a7fcf8718bcc88e.png)
JhHttpUtils 使用方法:
![](https://img.haomeiwen.com/i12175332/67480fb27e4e9318.png)
JhHttpUtils.js 代码:
/* 网络请求工具类 */
var isProduct = __wxConfig.envVersion =='release';
var isDevelop = __wxConfig.envVersion == 'develop';
/* get请求 */
function get(url, params) {
return request(url, "GET", params);
}
/* post请求 */
function post(url, params) {
return request(url, "POST", params);
}
/* 请求头 */
var _header = {
'content-type': 'application/x-www-form-urlencoded',
// 'version': '1.0.0',
}
/**
* function: 根据需求处理请求参数
* @params 请求参数
*/
function dealParams(params) {
if (isDevelop){
console.log("请求参数:", params);
}
return params;
}
const request = (url, method, params) => {
wx.showLoading({
title: '加载中',
})
return new Promise((resolve, reject) => {
wx.request({
url: url,
method: method,
data: dealParams(params),
header: _header,
success(res) {
wx.hideLoading();
if (isDevelop) {
console.log("请求返回数据:", res.data);
}
resolve(res.data)
},
fail(error) {
wx.hideLoading();
wx.showToast({
title: error,
icon: 'none',
duration: 2000
})
reject(error)
}
})
});
}
/* 通过module.exports方式提供给外部调用 */
module.exports = {
request,
getRequest: get,
postRequest: post,
}
/*
使用方法 :
1.在要使用的js文件导入
var http = require('../../../../JhHttpUtils/JhHttpUtils.js');
2. 调用
http.postRequest('url', prams).then(res => {
}).catch(error=>{
});
*/
APICongfig.js 代码:
/* 接口管理 */
var http = require('../JhHttpUtils/JhHttpUtils.js');
var API_BASE_URL = 'api地址';
/* 接口地址: */
var URL = {
api_getPageArrDic: API_BASE_URL + '/getPageArrDic', // 获取分页数组
}
/* 通过module.exports方式提供给外部调用 */
module.exports = {
//获取分页数据
getPageArrDic: (prams) => http.postRequest(URL.api_getPageArrDic, prams),
//获取分页数据2
getPageArrDic2: (prams) => {
console.log(URL.api_getPageArrDic + '-----------------------')
return http.postRequest(URL.api_getPageArrDic, prams)
}
}
/*
使用方法 :
1.在要使用的js文件导入
var API = require('../../../../JhHttpUtils/APICongfig.js');
2. 调用
API.getPageArrDic(prams).then(res => {
}).catch(error => {
});
*/
网友评论