auth.ts
1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import axios from 'axios'
import type { LoginForm, LoginResponse, User } from '@/types'
// 创建axios实例
const api = axios.create({
baseURL: 'http://localhost:8083/api',
timeout: 10000
})
// 请求拦截器
api.interceptors.request.use(
config => {
const token = localStorage.getItem('token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
},
error => {
return Promise.reject(error)
}
)
// 响应拦截器
api.interceptors.response.use(
response => {
return response.data
},
error => {
if (error.response?.status === 401) {
localStorage.removeItem('token')
localStorage.removeItem('userInfo')
window.location.href = '/login'
}
return Promise.reject(error)
}
)
// 登录
export function loginApi(data: LoginForm): Promise<LoginResponse> {
return api.post('/auth/login', data)
}
// 登出
export function logoutApi(): Promise<void> {
return api.post('/auth/logout')
}
// 获取用户信息
export function getUserInfoApi(): Promise<User> {
return api.get('/auth/userInfo')
}
// 刷新Token
export function refreshTokenApi(): Promise<{ token: string }> {
return api.post('/auth/refresh')
}
// 修改密码
export function changePasswordApi(data: {
oldPassword: string
newPassword: string
}): Promise<void> {
return api.post('/auth/changePassword', data)
}
// 获取验证码
export function getCaptchaApi(): Promise<{ captchaId: string; captchaImage: string }> {
return api.get('/auth/captcha')
}