博客列表 >小程序公共接口请求

小程序公共接口请求

意外的博客
意外的博客原创
2019年06月08日 21:23:041866浏览
//在公共文件utils/util.js下面

//地址;精确到控制器,方法在额外传入;
var requestUrl = "http://www.tp.cn/api/Home/";
var AppID = 'wx1678202cdfe457a6';
var AppSecret = 'b227e09e988d29045b4e0a1744f6d011';
//声明一个公共url方法;谁需要谁就调用;
function post(url, data, that, fun) {
//判断传入路径不为空;
if (url == 'undefined') {
return false;
}
//组装好完整的url地址;也就是接口;
var postUrl = requestUrl + url;
wx.request({
url: postUrl, //接口 ; 
data: data,   //参数;
method: "POST", //传入的方法;
dataType: "json", //传入的格式;
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
// that[fun](res.data.result);
//请求成功->得到接口数据(res.data)
that[fun](res.data); //返回a方法里的参数,加上接口里的参数;
// console.log(res.data);   //这个只获取到接口的值;通过回调返回给a方法;
},
fail: function (res) {
console.log('请求失败,请重试');
return {};
}
})
}

//登录接口
function login(url, data, fun, that) {
if (url == 'undefined') {
return false;
}
wx.login({
success: function (res) {
wx.request({
url: 'https://api.weixin.qq.com/sns/jscode2session',
data: {
appid: AppID,
secret: AppSecret,
js_code: res.code,
grant_type: 'authorization_code'
},
method: "POST",
dataType: "json",
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
// console.log(res);
data.unionid = 1;
post(url, data, fun, that);
},
fail: function (res) {
console.log('获取用户信息失败!');
return {};
}
})
}
});
}

//将方法post公开,也就是变成公共的;
module.exports.post = post;
//module.exports = {post:post}    和上面相等;
module.exports.login = login;


声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议