在理论开发中,前端须要跟后端约定HTTP申请头,这就须要对wx.request进行简略的封装
首先在util工具文件夹下新建ajax.js
其中内容:export const myAjax = (url,method,param,cb) => { let baseUrl = 'https://dev.xxxx.com:8090/'; // 申请地址,8090是跟后端约定好的端口号 let header = { "sessionCode": wx.getStorageSync("sessionCode"), "content-type": "application/json" } if(url == 'login' || url == 'register'){ header = { "content-type": "application/json" } // 登录和注册的时候,不必在header里传sessionCode } wx.request({ url: baseUrl + url, method, data: param, header, dataType: 'json', success: function (res) { if( res.data.code == 200 ){ // 返回正确回调 cb(res.data); }else{ if(res.data.code == -1){ // 无论在哪个页面未登录,都应用公共登录办法 publicLogin(()=>{ // 公共登录回调 myAjaxPost(url,param,cb); }); }else{ // 提醒弹框 wx.showModal({ title: '提醒!', confirmText: '确定', showCancel: false, content: res.data.msg ?? '', success: (res) => { if (res.confirm) { } } }) } } }, fail: function (err) {}})}
页面援用
首先在须要应用的页面引入该js文件const { myAjax } = require('../../util/ajax.js')
而后调用该专用办法
myAjax('getList', 'POST', { id: 3 }, (data) => { // 返回数据后的逻辑 })
题外话:
因为无论在哪个页面发现未登录都须要即时登录,所以还须要个公共登录的办法- 首先在util工具文件夹下新建public.js
而后引入方才封装的公共申请办法myAjax,因为登录胜利了,还要主动执行方才提醒“尚未登录”的那个接口import { myAjax } from './ajax.js'
公共登录办法如下:
export const publicLogin = (cb) => { wx.login({ // 跟后端约定好了传wx.login返回的code给他,这里请依据业务须要 success(res) { if (res.code) { let params = { loginToken: res.code, } myAjax('login', 'POST' params, async (res) => { if (res.sessionCode) { // 登录胜利 cb(); } else { // 登录失败,先去注册,注册之前,先获取手机号受权, // 而小程序官网规定手机号的受权必须用特定open-type的button // DOM组件的渲染必须依靠.wxml文件,所以这里间接跳到注册页 wx.navigateTo({ url: '/pages/register/index', success: function (e) { var page = getCurrentPages().pop(); if (page == undefined || page == null) return; // 在注册展现的时候,呈现受权手机号的button page.onShow(); } }) } }) } } })}