小程序开发——统一请求方法

it2022-06-27  89

一般我们习惯将请求接口的方法统一起来,变成公共方法 但是在小程序中,似乎遇到了一些问题,官方给的示例是:

this.setData({ name: 'MINA' })

this局限了请求的地方,似乎只能在每个业务页面内,setData方法的参数不够配置化 以下是我参考一些资料之后得到的解决方案

util.js

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;

调用api

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 () { } })

示例代码

https://github.com/zLulus/NotePractice/tree/dev3/MiniProgramDemo

转载于:https://www.cnblogs.com/Lulus/p/8945352.html


最新回复(0)