80 lines
2.3 KiB
JavaScript
80 lines
2.3 KiB
JavaScript
|
|
import { useMemberStore } from '@/stores'
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 添加拦截器
|
|||
|
|
* 拦截 request 请求
|
|||
|
|
* baseURL 设置请求ip地址和端口
|
|||
|
|
*/
|
|||
|
|
const baseURL = 'http://192.168.0.56:21627'
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 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,
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 4. 增加 token 请求头标识
|
|||
|
|
const memberStore = useMemberStore()
|
|||
|
|
const token = memberStore.userInfo.token
|
|||
|
|
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)
|
|||
|
|
}
|
|||
|
|
},
|
|||
|
|
fail(err) {
|
|||
|
|
// uni.showToast({
|
|||
|
|
// icon: 'none',
|
|||
|
|
// title: err,
|
|||
|
|
// })
|
|||
|
|
console.log(err, '请求失败')
|
|||
|
|
reject(err)
|
|||
|
|
},
|
|||
|
|
})
|
|||
|
|
})
|
|||
|
|
}
|