You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
115 lines
3.3 KiB
115 lines
3.3 KiB
/**
|
|
* 封装微信小程序请求,自动处理token
|
|
*/
|
|
const baseUrl='http://192.168.250.38:48080'
|
|
|
|
const request = (url, options = {}) => {
|
|
// 返回Promise,方便使用async/await
|
|
return new Promise((resolve, reject) => {
|
|
// 默认请求头
|
|
const header = {
|
|
'Content-Type': 'application/json',
|
|
...options.header
|
|
}
|
|
|
|
// 从本地存储获取token并添加到请求头
|
|
const token = wx.getStorageSync('token')
|
|
if (token) {
|
|
header['Authorization'] = `Bearer ${token}`
|
|
}
|
|
header['terminal'] = 10;
|
|
|
|
header['Accept'] = '*/*';
|
|
header['tenant-id'] = 1;
|
|
// 合并请求配置
|
|
const config = {
|
|
url:baseUrl+url,
|
|
method: options.method || 'GET',
|
|
data: options.data || {},
|
|
header,
|
|
// 成功回调
|
|
success: (res) => {
|
|
if (res.statusCode === 200) {
|
|
// 业务成功,返回数据
|
|
if(res.data&&res.data.code==401){
|
|
console.log("登录已过期,请重新登录")
|
|
// token失效或未登录,清除token并跳转登录页
|
|
wx.removeStorageSync('token')
|
|
wx.showToast({
|
|
title: '登录已过期,请重新登录',
|
|
icon: 'none'
|
|
})
|
|
|
|
// 记录当前页面,登录后返回
|
|
const pages = getCurrentPages()
|
|
const currentPage = pages[pages.length - 1]
|
|
wx.redirectTo({
|
|
url: `/pages/login/login?redirect=${currentPage.route}`
|
|
})
|
|
|
|
reject(new Error('未授权或token已过期'))
|
|
}else{
|
|
console.log("111")
|
|
resolve(res.data)
|
|
}
|
|
} else if (res.statusCode === 401) {
|
|
console.log("登录已过期,请重新登录")
|
|
// token失效或未登录,清除token并跳转登录页
|
|
wx.removeStorageSync('token')
|
|
wx.showToast({
|
|
title: '登录已过期,请重新登录',
|
|
icon: 'none'
|
|
})
|
|
|
|
// 记录当前页面,登录后返回
|
|
const pages = getCurrentPages()
|
|
const currentPage = pages[pages.length - 1]
|
|
wx.redirectTo({
|
|
url: `/pages/login/login?redirect=${currentPage.route}`
|
|
})
|
|
|
|
reject(new Error('未授权或token已过期'))
|
|
} else {
|
|
// 其他错误(如400、500等)
|
|
wx.showToast({
|
|
title: res.data?.message || '请求失败',
|
|
icon: 'none'
|
|
})
|
|
reject(new Error(`请求错误: ${res.statusCode}`))
|
|
}
|
|
},
|
|
// 失败回调(如网络错误)
|
|
fail: (err) => {
|
|
wx.showToast({
|
|
title: '网络异常,请稍后再试',
|
|
icon: 'none'
|
|
})
|
|
reject(err)
|
|
},
|
|
...options
|
|
}
|
|
console.log('config.url',config.url)
|
|
// 发起原生请求
|
|
wx.request(config)
|
|
})
|
|
}
|
|
|
|
// 快捷方法
|
|
request.get = (url, data, options = {}) => {
|
|
return request(url, { ...options, method: 'GET', data })
|
|
}
|
|
|
|
request.post = (url, data, options = {}) => {
|
|
return request(url, { ...options, method: 'POST', data })
|
|
}
|
|
|
|
request.put = (url, data, options = {}) => {
|
|
return request(url, { ...options, method: 'PUT', data })
|
|
}
|
|
|
|
request.delete = (url, data, options = {}) => {
|
|
return request(url, { ...options, method: 'DELETE', data })
|
|
}
|
|
|
|
module.exports = request
|
|
|
|
|