init: initial commit
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
import axios, { type AxiosError, type AxiosRequestConfig, type InternalAxiosRequestConfig } from 'axios'
|
||||
|
||||
const API_BASE_URL = '/api'
|
||||
|
||||
const AUTH_WHITELIST = ['/auth/captcha', '/auth/login']
|
||||
|
||||
const request = axios.create({
|
||||
baseURL: API_BASE_URL,
|
||||
timeout: 30000,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
request.interceptors.request.use(
|
||||
(config: InternalAxiosRequestConfig) => {
|
||||
const isWhitelisted = AUTH_WHITELIST.some(path => config.url?.startsWith(path))
|
||||
if (!isWhitelisted) {
|
||||
const token = localStorage.getItem('token')
|
||||
if (token) config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
if (config.data instanceof FormData) {
|
||||
config.headers.delete('Content-Type')
|
||||
}
|
||||
return config
|
||||
},
|
||||
(error: AxiosError) => Promise.reject(error)
|
||||
)
|
||||
|
||||
request.interceptors.response.use(
|
||||
response => {
|
||||
const res = response.data
|
||||
if (res.code !== undefined && res.code !== 200) {
|
||||
if (res.code === 401) {
|
||||
localStorage.removeItem('token')
|
||||
localStorage.removeItem('user')
|
||||
window.location.href = '/login'
|
||||
}
|
||||
return Promise.reject(new Error(res.msg || '请求失败'))
|
||||
}
|
||||
return res
|
||||
},
|
||||
(error: AxiosError) => {
|
||||
if (error.response?.status === 401) {
|
||||
localStorage.removeItem('token')
|
||||
localStorage.removeItem('user')
|
||||
window.location.href = '/login'
|
||||
}
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
export function get<T = unknown>(url: string, params?: Record<string, unknown>, config?: AxiosRequestConfig): Promise<T> {
|
||||
return request.get(url, { params, ...config })
|
||||
}
|
||||
|
||||
export function post<T = unknown>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T> {
|
||||
return request.post(url, data, config)
|
||||
}
|
||||
|
||||
export function put<T = unknown>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T> {
|
||||
return request.put(url, data, config)
|
||||
}
|
||||
|
||||
export function del<T = unknown>(url: string, config?: AxiosRequestConfig): Promise<T> {
|
||||
return request.delete(url, config)
|
||||
}
|
||||
|
||||
export default request
|
||||
|
||||
export interface ApiResponse<T = unknown> { code: number; data: T; msg: string }
|
||||
export interface PageResult<T = unknown> { list: T[]; page: number; pageSize: number; total: number }
|
||||
export interface PageParams { current: number; pageSize: number; keyword?: string }
|
||||
@@ -0,0 +1,6 @@
|
||||
import { type ClassValue, clsx } from 'clsx'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
Reference in New Issue
Block a user