通常咱们习惯将请求接口的方法统一块儿来,变成公共方法
可是在小程序中,彷佛遇到了一些问题,官方给的示例是:git
this.setData({ name: 'MINA' })
this局限了请求的地方,彷佛只能在每一个业务页面内,setData方法的参数不够配置化
如下是我参考一些资料以后获得的解决方案github
var apiHost = "....."; //url添加最后的相对路径便可 function getRequest(url, that, targetName) { wx.request({ url: apiHost + url, method: 'GET', header: { 'content-type': 'application/json' // 默认值 }, success: function (res) { var param = {}; param[targetName] = res.data; that.setData(param); }, fail: function (error) { console.log(error); } }) } function postRequest(url, data, that, targetName ) { var token='你的令牌'; //好比存储在Storage中 wx.request({ url: apiHost + url, data: data, method: 'POST', header: { 'content-type': 'application/json', // 默认值 'Authorization': "Bearer " + token }, success: function (res) { var param = {}; param[targetName] = res.data; that.setData(param); }, fail: function (error) { console.log(error); } }) } module.exports.getRequest = getRequest; module.exports.postRequest = postRequest;
const util = require('../../utils/util.js') Page({ data: { logInResult:{}, sessionKey:"", }, logIn:function(e){ //登陆某系统 util.postRequest('/Account/LogInForMiniProgram', { "UserName": this.data.userName, "Password": this.data.password }, this, "logInResult"); }, wxLogInAndGetSessionKey: function (e) { //注意做用域,此处,在wx的方法里面拿到的this不对(http://jsrocks.org/cn/2014/10/arrow-functions-and-their-scope) var that = this; wx.login({ success: function (res) { console.log(res) if (res.code) { //调用后端接口得到sessionkey util.postRequest('/AccountForMiniProgram/WechatGetSessionKey', { id: res.code }, that, "sessionKey"); } else { console.log('登陆失败!' + res.errMsg) } } }); }, onLoad: function () { } })
示例代码json