2024-11-18 09:05:38 +08:00
|
|
|
|
import { useMemberStore } from '@/stores'
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 添加拦截器
|
|
|
|
|
|
* 拦截 request 请求
|
|
|
|
|
|
* baseURL 设置请求ip地址和端口
|
|
|
|
|
|
*/
|
2024-11-18 16:52:12 +08:00
|
|
|
|
const baseURL = 'http://192.168.2.246:18080'
|
2024-11-18 09:05:38 +08:00
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* httpInterceptor 分别拦截 request 和 uploadFile 请求
|
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
|
|
// 添加请求拦截
|
|
|
|
|
|
const httpInterceptor = {
|
|
|
|
|
|
invoke(options) {
|
|
|
|
|
|
// 1. 先判断请求 url 是否为完整的 http 请求路径 如果不是则拼接 baseURL
|
|
|
|
|
|
if (!options.url.startsWith('http')) {
|
|
|
|
|
|
options.url = baseURL + options.url
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 2. 设置请求超时时间,默认为60s,设置为 10s
|
|
|
|
|
|
options.timeout = 10000
|
|
|
|
|
|
|
|
|
|
|
|
// 3. 增加小程序端请求头标识
|
|
|
|
|
|
options.header = {
|
|
|
|
|
|
// 'source-client': 'mini',
|
|
|
|
|
|
...options.header,
|
|
|
|
|
|
}
|
2024-11-18 16:52:12 +08:00
|
|
|
|
|
2024-11-18 09:05:38 +08:00
|
|
|
|
// 4. 增加 token 请求头标识
|
|
|
|
|
|
const memberStore = useMemberStore()
|
2024-11-18 16:52:12 +08:00
|
|
|
|
// const token = memberStore.userInfo.token
|
|
|
|
|
|
const token = "eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6IjQ2NDdmYjlkLWI5OTItNDRiNy05MTdkLTMwZjg0ZjUxYzM5MCIsInVzZXJuYW1lIjoiYWRtaW4ifQ.9xM5bFhrmHK09-4ZgL5SS8WraNIJjIijuB-1P0lJF-n0KlVM5Bglvyjltk1NQbdqgi1hwRocZS1OU41cLiwuig"
|
2024-11-18 09:05:38 +08:00
|
|
|
|
if (token) {
|
|
|
|
|
|
options.header.Authorization = token
|
|
|
|
|
|
}
|
|
|
|
|
|
},
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
uni.addInterceptor('request', httpInterceptor)
|
|
|
|
|
|
uni.addInterceptor('uploadFile', httpInterceptor)
|
|
|
|
|
|
|
|
|
|
|
|
// 设置http请求
|
|
|
|
|
|
export const http = (options) => {
|
|
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
|
|
uni.request({
|
|
|
|
|
|
...options,
|
|
|
|
|
|
success(res) {
|
|
|
|
|
|
// 1. 判断是否请求成功
|
|
|
|
|
|
if (res.statusCode >= 200 && res.statusCode < 300) {
|
|
|
|
|
|
resolve(res.data)
|
|
|
|
|
|
} else if (res.statusCode === 401) {
|
|
|
|
|
|
// 2. 401 表示token过期 去往登录页重新登录
|
|
|
|
|
|
const memberStore = useMemberStore()
|
|
|
|
|
|
memberStore.clearUserInfo()
|
|
|
|
|
|
uni.navigateTo({
|
|
|
|
|
|
url: '/pages/login/index',
|
|
|
|
|
|
})
|
|
|
|
|
|
reject(res)
|
|
|
|
|
|
} else {
|
|
|
|
|
|
// 3. 其他错误
|
|
|
|
|
|
// uni.showToast({
|
|
|
|
|
|
// icon: 'none',
|
|
|
|
|
|
// title: '请求错误',
|
|
|
|
|
|
// })
|
|
|
|
|
|
reject(res)
|
|
|
|
|
|
}
|
2024-11-18 16:52:12 +08:00
|
|
|
|
console.log(res)
|
2024-11-18 09:05:38 +08:00
|
|
|
|
},
|
|
|
|
|
|
fail(err) {
|
|
|
|
|
|
// uni.showToast({
|
|
|
|
|
|
// icon: 'none',
|
|
|
|
|
|
// title: err,
|
|
|
|
|
|
// })
|
|
|
|
|
|
console.log(err, '请求失败')
|
|
|
|
|
|
reject(err)
|
|
|
|
|
|
},
|
|
|
|
|
|
})
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|