原码笔记

原码笔记

微信小程序 request请求封装

小诸哥 0

封装代码 

我的项目中是将代码放在了utils里面,创建了一个js文件然后把下面的代码放进去

get和post调用方法差不多,只是差了一个data

ar apiurl = '请求地址';


function http_post(controller, data, cb) {

wx.request({

url: apiurl + controller,

data: data,

method: 'post',

header: { 'Content-Type': 'application/x-www-form-urlencoded' },

success: function (res) {

return typeof cb == "function" && cb(res.data)

},

fail: function (res) {

return typeof cb == "function" && cb(false)

}

})

}
function http_get(controller,cb) {
//加载事件
wx.showLoading({

title: '数据加载中',

});
wx.request({

url: apiurl + controller,

method: 'get',

header: { 'Content-Type': 'application/x-www-form-urlencoded' },

success: function (res) {
wx.hideLoading();
return typeof cb == "function" && cb(res.data)

},

fail: function (res) {

return typeof cb == "function" && cb(false)

}

})

}
module.exports = {

http_post: http_post,//post请求
http_get:http_get,//get请求

}

在要请求的地方调用下面的代码就可以

post调用

var wxq = require('../../utils/wxrequest.js');

var data={
img_url: this.data.imglist,
contents: content,
phone: phone
}

//获取公告
wxq.http_post('/article/create', data, function (res) {
console.log(res)
})

get调用

var wxq = require('../../utils/wxrequest.js');
//获取公告
wxq.http_get('/index/notice', function(res) {
console.log(res)
})


标签: 小程序 移动互联网