import axios from 'axios'
import qs from 'qs'
import { ElMessage } from 'element-plus'
import store from '@/store'
import cache from '@/utils/cache'
// axios实例
const service = axios.create({
baseURL: import.meta.env.VITE_API_URL as any,
timeout: 60000,
headers: { 'Content-Type': 'application/json;charset=UTF-8' }
})
// 请求拦截器
service.interceptors.request.use(
(config) => {
const userStore = store.userStore
if (userStore?.token) {
config.headers.Authorization = 'Bearer ' + userStore.token
}
config.headers['Accept-Language'] = cache.getLanguage()
// 追加时间戳,防止GET请求缓存
if (config.method?.toUpperCase() === 'GET') {
config.params = { ...config.params, t: new Date().getTime() }
}
if (Object.values(config.headers).includes('application/x-www-form-urlencoded')) {
config.data = qs.stringify(config.data)
}
return config
},
error => {
return Promise.reject(error)
}
)
// 响应拦截器
service.interceptors.response.use(
response => {
if (response.status !== 200) {
return Promise.reject(new Error(response.statusText || 'Error'))
}
const res = response.data
// 响应成功
if (res.code === 0) {
return res
}
// 错误提示
ElMessage.error(res.msg)
// 没有权限,如:未登录、登录过期等,需要跳转到登录页
if (res.code === 401) {
store.userStore.setToken('')
location.reload()
}
return Promise.reject(new Error(res.msg || 'Error'))
},
error => {
ElMessage.error(error.message)
return Promise.reject(error)
}
)
// 导出 axios 实例
export default service
store.js
import { userStore } from './modules/user'
import { routerStore } from './modules/router'
import { appStore } from './modules/app'
import { tabsStore } from './modules/tabs'
const store: any = {}
export const registerStore = () => {
store.userStore = userStore()
store.routerStore = routerStore()
store.appStore = appStore()
store.tabsStore = tabsStore()
}
export default store
user.js
import { defineStore } from 'pinia'
import { useLoginApi, useLogoutApi } from '@/api/login'
import { useUserInfoApi } from '@/api/user'
import cache from '@/utils/cache'
export const userStore = defineStore('userStore', {
state: () => ({
user: {
id: '',
username: '',
email: '',
avatar: ''
},
token: cache.getToken()
}),
actions: {
setUser(val: any) {
this.user = val
},
setToken(val: any) {
this.token = val
cache.setToken(val)
},
// 用户登录
async loginAction(loginForm: any) {
const res: any = await useLoginApi(loginForm)
this.setToken(res.access_token)
},
// 获取用户信息
async getUserInfoAction() {
const { data } = await useUserInfoApi()
this.setUser(data)
},
// 用户退出
async logoutAction() {
await useLogoutApi()
// 移除 token
this.setToken(null)
}
}
})
页面使用
import service from '@/utils/request'
export const useLoginApi = (data: any) => {
return service.post('/data/login.json', data, {
auth: {
username: 'web',
password: '123456'
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
}
export const useLogoutApi = () => {
return service.post('/data/success.json')
}