var uelNet = " 請求地址"
/**
* 供外部post請求調(diào)用
*/
function post(params, onStart, onSuccess, onFailed) {
request( params, "POST", onStart, onSuccess, onFailed);
}
/**
* 供外部get請求調(diào)用
*/
function get( params, onStart, onSuccess, onFailed) {
request( params, "GET", onStart, onSuccess, onFailed);
}
// 沒有請求頭
function getNoHeader(params, onStart, onSuccess, onFailed) {
noHeaderequest(params, "GET", onStart, onSuccess, onFailed);
}
/**
* function: 封裝網(wǎng)絡(luò)請求
* @url URL地址
* @params 請求參數(shù)
* @method 請求方式:GET/POST
* @onStart 開始請求,初始加載loading等處理
* @onSuccess 成功回調(diào)
* @onFailed 失敗回調(diào)
*/
function request( params, method, onStart, onSuccess, onFailed) {
onStart(); //request start
wx.request({
url: uelNet,
data: {
params: JSON.stringify(params)
},
method: method,
header: { 'content-type': 'application/json', 'accessUser': getApp().globalData.userInfo.colUid },
success: function (res) {
if (res.data) {
/** start 根據(jù)需求 接口的返回狀態(tài)碼進(jìn)行處理 */
if (res.statusCode == 200) {
onSuccess(res); //request success
} else {
onFailed(res.data.msg); //request failed
}
/** end 處理結(jié)束*/
}
},
fail: function (error) {
onFailed(""); //failure for other reasons
}
})
}
/**
* function: 封裝網(wǎng)絡(luò)請求
* @url URL地址
* @params 請求參數(shù)
* @method 請求方式:GET/POST
* @onStart 開始請求,初始加載loading等處理
* @onSuccess 成功回調(diào)
* @onFailed 失敗回調(diào)
*/
function noHeaderequest(params, method, onStart, onSuccess, onFailed) {
onStart(); //request start
wx.request({
url: uelNet,
data: {
params: JSON.stringify(params)
},
method: method,
header: { 'content-type': 'application/json' },
success: function (res) {
if (res.data) {
/** start 根據(jù)需求 接口的返回狀態(tài)碼進(jìn)行處理 */
if (res.statusCode == 200) {
onSuccess(res); //request success
} else {
onFailed(res.data.msg); //request failed
}
/** end 處理結(jié)束*/
}
},
fail: function (error) {
onFailed(""); //failure for other reasons
}
})
}
/**
* function: 根據(jù)需求處理請求參數(shù):添加固定參數(shù)配置等
* @params 請求參數(shù)
*/
function dealParams(params) {
return params;
}
module.exports = {
postRequest: post,
getRequest: get,
getNoHeader: getNoHeader
}
頁面使用
引用
var netUtil = require('')
使用
//params 參數(shù)
//this.onStart, 開始請求
//this.onSuccess 請求成功
//this.onFailed 請求失敗
netUtil.getRequest(params, this.onStart, this.onSuccess, this.onFailed); //調(diào)用get方法