http封装js: httpService.js
import {
httpMethod
} from "./commonConst";
function wxPromisify() {
return function (obj = {}) {
return new Promise((resolve, reject) => {
obj.success = function (res) {
resolve(res.data);
};
obj.fail = function (error) {
reject(error);
};
wx.request(obj);
});
};
}
//无论promise对象最后状态如何都会执行
Promise.prototype.finally = function (callback) {
let P = this.constructor;
return this.then(
value => P.resolve(callback()).then(() => value),
reason => P.resolve(callback()).then(() => { throw reason; })
);
};
function postMethod(url, headerObj, bodyObj) {
var getRequest = wxPromisify(wx.request);
return getRequest({
url: url,
header: headerObj,
data: bodyObj,
method: httpMethod.POST
});
}
function getMethod(url, headerObj) {
var getRequest = wxPromisify();
return getRequest({
url: url,
header: headerObj,
method: httpMethod.GET
});
}
function deleteMethod(url, headerObj) {
var getRequest = wxPromisify();
return getRequest({
url: url,
header: headerObj,
method: httpMethod.DELETE
});
}
function putMethod(url, headerObj, bodyObj) {
var getRequest = wxPromisify();
return getRequest({
url: url,
header: headerObj,
data: bodyObj,
method: httpMethod.PUT
});
}
// 将方法导出
module.exports = {
get: getMethod,
post: postMethod,
delete: deleteMethod,
put: putMethod
};
使用示例: org.js
import {
post
} from '../../utils/httpServices'
import {
URL
} from '../../utils/constants'
/**
* 添加
*/
function add(headerObj, bodyObj) {
return post(URL.add, headerObj, bodyObj);
}
/**
* 查询列表
*/
function list(headerObj, bodyObj) {
return post(URL.list, headerObj, bodyObj);
}
/**
* 删除
*/
function delete(headerObj, bodyObj) {
return post(URL.delete, bodyObj, headerObj);
}
/**
* 更新
*/
function update(headerObj, bodyObj) {
return post(URL.update, headerObj, bodyObj);
}
/**
* 检索
*/
function search(headerObj, bodyObj) {
return post(URL.search, bodyObj, headerObj);
}
module.exports.orgService = {
add: add,
delete: delete,
update: update,
list: list,
search: search
};
调用方法:update.js
import {
orgService
} from '../../../services/org';
Page({
...
...
data: {
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function () {
this.getUpdateData();
},
/**
* 更新
*/
getUpdateData: async function() {
let headerObj = { ... };
let bodyObj = {...};
return await orgService.update(headerObj, bodyObj).then(res => {
console.log('res',res);
}).catch(error => {
console.log('error',error);
})
},
})
constants.js
// host
const testHost = "https://test.com";
// 微信家属版用接口path
const addPath = '/api/add';
const listPath = '/api/list';
const searchPath = '/api/search';
const updatePath = '/api/infoupdate';
const deletePath = '/api/delete';
// pathURL
module.exports.URL = {
add: testHost + addPath ,
list: testHost + listPath ,
search: testHost + searchPath ,
update: testHost + updatePath ,
delete: testHost + deletePath
}