1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| import checkLogin from "./checkLogin"; import {baseUrl} from "./config";
const toast = (title, reject) => { wx.showToast({ title, icon: 'none' }) reject(title) }
const request = (url, method = "GET", data = {}, isLoading = true) => { return new Promise((resolve, reject) => { if (isLoading) { wx.showLoading({title: '加载中..'}) } wx.request({ url: baseUrl + url, method, data, header: { Authorization: 'Bearer ' + wx.getStorageSync('access_token') || '' }, success(res) { let msg = '' const {statusCode} = res if (statusCode < 400) { resolve(res.data) } else if (statusCode === 400) { msg = res.data.message } else if (statusCode === 401) { if (res.data.message == 'Unauthorized') { msg = '账号密码错误' } else { wx.removeStorageSync('access_token') wx.removeStorageSync('userInfo') checkLogin() } } else if (statusCode === 403) { msg = '没有权限' } else if (statusCode === 404) { msg = '未找到资源' } else if (statusCode === 422) { const {errors} = res.data msg = errors[Object.keys(errors)[0]][0] } else if (statusCode === 429) { msg = '请稍后再试' } else { msg = '请求异常' }
if(msg) toast(msg, reject) }, fail(e) { toast('服务器异常') reject(e) }, complete() { wx.hideLoading() } }) }) }
const e = { request, get: (url, data = {}, isLoading = true) => request(url, 'GET', data, isLoading), post: (url, data = {}, isLoading = true) => request(url, 'POST', data, isLoading), patch: (url, data = {}, isLoading = true) => { data = { ...data, _method: 'PATCH' } return request(url, 'POST', data, isLoading) }, put: (url, data = {}, isLoading = true) => request(url, 'put', data, isLoading), delete: (url, data = {}, isLoading = true) => request(url, 'DELETE', data, isLoading), }
module.exports = e
|