1.逻辑是这样的用户登录成功,我们把token和用户的信息存储到本地
2.config是存放baseUrl的文件
1 const config = { 2 3 url: ‘https:XXX/index.php‘ 4 } 5 export { 6 config 7 }
3.在请求库requset.js, http请求函数返回的是一个 promise 的对象,利用微信的wx.request接口,请求成功的时候resolve,请求失败时reject
1 import { 2 config 3 } from ‘./config.js‘ 4 import Toast from ‘../ui/dist/toast/toast‘ 5 6 //公共请求接口方法 7 var onoff = true 8 const http = (method, url, data) => { 9 10 //加载动画 11 wx.showLoading({ 12 title: ‘加载中...‘, 13 showCancel: true, 14 mask: true 15 }); 16 17 //用户信息对象 18 19 let loginInfo = wx.getStorageSync(‘login_info‘) ? JSON.parse(wx.getStorageSync(‘login_info‘)) : { 20 token: null, 21 id: null 22 }; 23 return new Promise(function(resolve, reject) { 24 25 wx.request({ 26 method: method, //请求类型 27 url: config.url + url, //请求地址 28 header: { //请求头 29 ‘content-type‘: ‘application/json‘, 30 ‘token‘: loginInfo.token, 31 ‘id‘: loginInfo.id 32 }, 33 data: data, //请求参数 34 success: res => { 35 wx.hideLoading(); //请求完成关闭加载动画 36 //token过期 清除用户信息(根据后端返回相应的状态码就行拦截) 37 if (res.data.error_code == 21000) { 38 console.log("登录超时") 39 if(!onoff) return 40 wx.showModal({ 41 title: ‘提示‘, 42 content: ‘登录已过期‘, 43 confirmText:"重新登录", 44 showCancel:false, 45 success (res) { 46 if (res.confirm) { 47 wx.removeStorageSync("login_info"); 48 wx.setStorageSync(‘isLogin‘, false); 49 wx.reLaunch({ url: "/pages/login/pages/guide/guide" }); 50 // onoff=!onoff; 51 } 52 } 53 }) 54 55 return 56 } 57 if (res.statusCode == 200) { 58 onoff=true; 59 resolve(res.data); //成功回调 60 } else { 61 console.log(res.data, 666) 62 wx.showToast({ 63 title:res.data.msg ||‘网络错误!‘, 64 icon: ‘none‘, 65 duration: 2000 66 }) 67 } 68 }, 69 fail: err => { 70 console.log(err,"请求失败了") 71 reject(err); //失败回调 72 wx.hideLoading(); //请求完成关闭加载动画 73 83 }, 84 complete: info => { 85 86 87 } 88 }) 89 }) 90 } 91 92 const Get = (url, data) => http(‘GET‘, url, data) 93 const Post = (url, data) => http(‘POST‘, url, data) 94 const PUT = (url, data) => http(‘PUT‘, url, data) 95 const DELETE = (url, data) => http(‘DELETE‘, url, data) 96 export { 97 Get, 98 Post, 99 DELETE, 100 PUT 101 }
4.api文件
1 import { 2 Get, 3 Post, 4 PUT 5 } from ‘../utils/request.js‘ 6 //账号登录接口 7 export function loginHandle(params) { 8 return Post(‘/api/v1/login‘, params) 9 }
5.页面调用
import {
loginHandle
} from ‘../utils/request.js‘
loginHandle().then(res=>{
console.log(res,"请求成功的返回值")
})