在实际开发中,前端需要跟后端约定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();
}
})
}
})
}
}
})
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。