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,"請求成功的返回值")
})
