微信小程序网络请求封装示例 网络请求 网络请求小程序提供了wx.request, 仔细看一下 api,这不就是n年前的 $.ajax 吗,好古老啊。 // 官方例子 wx.request({ url: 'test.php', //仅为示例,并非真实的接口地址 data: { x: '' , y: '' }, header: { 'content-type': 'application/json' // 默认值 }, success: function(res) { console.log(res.data) } }) 小程序支持ES6,那么就应该支持Promise 了,很开心~, 话不多说直接上代码吧 Promise封装 const baseUrl = 'http://api.it120.cc'; const http = ({ url = '', param = {}, ...other } = {}) => { wx.showLoading({ title: '请求中,请耐心等待..' }); let timeStart = Date.now(); return new Promise((resolve, reject) => { wx.request({ url: getUrl(url), data: param, header: { 'content-type': 'application/json' // 默认值 ,另一种是 "content-type": "application/x-www-form-urlencoded" }, ...other, complete: (res) => { wx.hideLoading(); console.log(`耗时${Date.now() - timeStart}`); if (res.statusCode >= 200 && res.statusCode < 300) { resolve(res.data) } else { reject(res) } } }) }) } const getUrl = (url) => { if (url.indexOf('://') == -1) { url = baseUrl + url; } return url } // get方法 const _get = (url, param = {}) => { return http({ url, param }) } const _post = (url, param = {}) => { return http({ url, param, method: 'post' }) } const _put = (url, param = {}) => { return http({ url, param, method: 'put' }) } const _delete = (url, param = {}) => { return http({ url, param, method: 'put' }) } module.exports = { baseUrl, _get, _post, _put, _delete } 使用 const api = require('../../utils/api.js') // 单个请求 api.get('list').then(res => { console.log(res) }).catch(e => { console.log(e) }) // 一个页面多个请求 Promise.all([ api.get('list'), api.get(`detail/${id}`) ]).then(result => { console.log(result) }).catch(e => { console.log(e) }) 登陆问题 做一个应用,肯定避免不了登录操作。用户的个人信息啊,相关的收藏列表等功能都需要用户登录之后才能操作。一般我们使用token做标识。 小程序并没有登录界面,使用的是 wx.login 。 wx.login 会获取到一个 code,拿着该 code 去请求我们的后台会最后返回一个token到小程序这边,保存这个值为 token 每次请求的时候带上这个值。 一般还需要把用户的信息带上比如用户微信昵称,微信头像等,这时候就需要使用 wx.getUserInfo ,这里涉及到一个用户授权的问题 带上用户信息就够了嘛? too young too simple!我们的项目不可能只有小程序,相应的微信公众平台可能还有相应的App,我们需要把账号系统打通,让用户在我们的项目中的账户是同一个。这就需要用到微信开放平台提供的 UnionID 。 登陆 //app.js App({ onLaunch: function () { console.log('App onLaunch'); var that = this; // 获取商城名称 wx.request({ url: 'http://api.it120.cc/'+ that.globalData.subDomain +'/config/get-value', data: { key: 'mallName' }, success: function(res) { wx.setStorageSync('mallName', res.data.data.value); } }) this.login(); this.getUserInfo(); }, login : function () { var that = this; var token = that.globalData.token; // 如果有token if (token) { // 检查token是否有效 wx.request({ url: 'http://api.it120.cc/' + that.globalData.subDomain + '/user/check-token', data: { token: token }, success: function (res) { // 如果token失效了 if (res.data.code != 0) { that.globalData.token = null; that.login(); // 重新登陆 } } }) return; } // 【1】调用微信自带登陆 wx.login({ success: function (res) { // 【2】 拿到code去访问我们的后台换取其他信息 wx.request({ url: 'http://api.it120.cc/'+ that.globalData.subDomain +'/user/wxapp/login', data: { code: res.code }, success: function(res) { // 如果说这个code失效的 if (res.data.code == 10000) { // 去注册 that.registerUser(); return; } // 如果返回失败了 if (res.data.code != 0) { // 登录错误 wx.hideLoading(); // 提示无法登陆 wx.showModal({ title: '提示', content: '无法登录,请重试', showCancel:false }) return; } // 【3】 如果成功后设置token到本地 that.globalData.token = res.data.data.token; // 保存用户信息 wx.setStorage({ key: 'token', data: res.data.data.token }) } }) } }) }, // 注册?? [这个看需求] registerUser: function () { var that = this; wx.login({ success: function (res) { var code = res.code; // 微信登录接口返回的 code 参数,下面注册接口需要用到 wx.getUserInfo({ success: function (res) { var iv = res.iv; var encryptedData = res.encryptedData; // 下面开始调用注册接口 wx.request({ url: 'http://api.it120.cc/' + that.globalData.subDomain +'/user/wxapp/register/complex', data: {code:code,encryptedData:encryptedData,iv:iv}, // 设置请求的 参数 success: (res) =>{ wx.hideLoading(); that.login(); } }) } }) } }) }, // 获取用户信息 getUserInfo:function() { wx.getUserInfo({ success:(data) =>{ this.globalData.userInfo = data.userInfo; wx.setStorage({ key: 'userInfo', data: data.userInfo }) return this.globalData.userInfo; } }) }, globalData:{ userInfo:null, subDomain:"34vu54u7vuiuvc546d", token: null } }) 授权问题 getUserInfo: function () { // 先调用wx.getSetting 获取用户权限设置 wx.getSetting({ success(res) { console.log('1'); if (!res.authSetting['scope.userInfo']) { wx.authorize({ scope: 'scope.userInfo', success() { // 用户已经同意小程序使用录音功能,后续调用 wx.getUserInfo接口不会弹窗询问 wx.getUserInfo({ success: (data) => { this.globalData.userInfo = data.userInfo; wx.setStorage({ key: 'userInfo', data: data.userInfo }) return this.globalData.userInfo; } }) } }) } else { console.log(2); } } }) }, 小结 网络请求这块,算目前开发项目中必不可少的一块加油~~ 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持中文源码网。