59 lines
1.4 KiB
JavaScript
59 lines
1.4 KiB
JavaScript
const app = getApp()
|
|
|
|
function getBaseURL() {
|
|
return app.globalData.baseURL || 'http://127.0.0.1:5000/api'
|
|
}
|
|
|
|
function getToken() {
|
|
return app.globalData.token || wx.getStorageSync('token') || ''
|
|
}
|
|
|
|
function request({ url, method = 'GET', data = {}, header = {} }) {
|
|
return new Promise((resolve, reject) => {
|
|
const token = getToken()
|
|
const headers = {
|
|
'Content-Type': 'application/json',
|
|
...header
|
|
}
|
|
|
|
if (token) {
|
|
headers.Authorization = `Bearer ${token}`
|
|
}
|
|
|
|
wx.request({
|
|
url: `${getBaseURL()}${url}`,
|
|
method,
|
|
data,
|
|
header: headers,
|
|
success: (res) => {
|
|
if (res.statusCode === 401) {
|
|
app.clearAuth()
|
|
wx.showToast({ title: '登录已过期,请重新登录', icon: 'none' })
|
|
setTimeout(() => wx.reLaunch({ url: '/pages/login/index' }), 600)
|
|
reject(new Error('Unauthorized'))
|
|
return
|
|
}
|
|
|
|
const body = res.data || {}
|
|
if (body.code === 0) {
|
|
resolve(body.data)
|
|
return
|
|
}
|
|
|
|
const message = body.message || '请求失败'
|
|
wx.showToast({ title: message, icon: 'none' })
|
|
reject(new Error(message))
|
|
},
|
|
fail: (err) => {
|
|
const msg = (err && err.errMsg) || '网络异常,请检查后端地址'
|
|
wx.showToast({ title: msg, icon: 'none' })
|
|
reject(err)
|
|
}
|
|
})
|
|
})
|
|
}
|
|
|
|
module.exports = {
|
|
request
|
|
}
|