PC端封装
import axios from 'axios'
import axiosAdapterUniapp from 'axios-adapter-uniapp'
const baseURL = 'http://www.ajing.fun:8090'
const instance = axios.create({
// TODO 1. 基础地址,超时时间
baseURL,
timeout: 5000,
adapter: axiosAdapterUniapp
})
//请求,携带token
instance.interceptors.request.use(
(config) => {
const token= uni.getStorageSync('token')
if (token) {
console.log('请求携带token', token)
config.headers.Authorization = token
}
return config
},
(err) => Promise.reject(err)
)
//响应
instance.interceptors.response.use(
(res) => {
console.log(res);
if (res.code === 0) {
uni.showToast({
icon:'error',
title:'错误'
})
} else {
console.log(res.data);
return res.data
}
return res.data
},
(err) => {
// TODO 5. 处理401错误
// if (err.response.status === 401) {
// uni.showToast({
// icon:'error',
// title:'认证信息过期,请重新登录!'
// })
// }
// TODO 6. 处理其它错误
uni.showToast({
icon:'error',
title:'网络请求失败!'
})
return Promise.reject(err)
}
)
export default instance
export { baseURL }
Uniapp封装
import axios from 'axios'
import axiosAdapterUniapp from 'axios-adapter-uniapp'
const baseURL = 'http://www.ajing.fun:8090'
const instance = axios.create({
// TODO 1. 基础地址,超时时间
baseURL,
timeout: 5000,
adapter: axiosAdapterUniapp
})
//请求,携带token
instance.interceptors.request.use(
(config) => {
const token= uni.getStorageSync('token')
if (token) {
console.log('请求携带token', token)
config.headers.Authorization = token
}
return config
},
(err) => Promise.reject(err)
)
//响应
instance.interceptors.response.use(
(res) => {
console.log(res);
if (res.code === 0) {
uni.showToast({
icon:'error',
title:'错误'
})
} else {
console.log(res.data);
return res.data
}
return res.data
},
(err) => {
// TODO 5. 处理401错误
// if (err.response.status === 401) {
// uni.showToast({
// icon:'error',
// title:'认证信息过期,请重新登录!'
// })
// }
// TODO 6. 处理其它错误
uni.showToast({
icon:'error',
title:'网络请求失败!'
})
return Promise.reject(err)
}
)
export default instance
export { baseURL }