初始化fateverse
This commit is contained in:
16
src/utils/auth.ts
Normal file
16
src/utils/auth.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import Cookies from "js-cookie";
|
||||
|
||||
// 设置token
|
||||
export const setToken = (token: string): void => {
|
||||
Cookies.set('Authorization', token)
|
||||
}
|
||||
|
||||
// 获取token
|
||||
export const getToken = ():string | undefined => {
|
||||
return Cookies.get('Authorization')
|
||||
}
|
||||
|
||||
// 清除token
|
||||
export const removeToken = (): void => {
|
||||
Cookies.remove('Authorization')
|
||||
}
|
||||
75
src/utils/request.ts
Normal file
75
src/utils/request.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import { IResponse, IToken } from "@/type";
|
||||
import axios, { InternalAxiosRequestConfig, AxiosInstance, AxiosRequestConfig } from "axios";
|
||||
import Cookie from 'js-cookie'
|
||||
import { getToken, removeToken } from "./auth";
|
||||
import { message } from "antd";
|
||||
|
||||
const service: AxiosInstance = axios.create({
|
||||
baseURL: import.meta.env.VITE_BASEURL,
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
timeout: 6000
|
||||
})
|
||||
|
||||
// 请求前拦截
|
||||
service.interceptors.request.use((config: InternalAxiosRequestConfig) => {
|
||||
const Authorization: IToken = getToken() || ''
|
||||
if (config && config.headers && Authorization) {
|
||||
config.headers.Authorization = Authorization
|
||||
}
|
||||
return config
|
||||
})
|
||||
|
||||
const request = async <T = any>(config: AxiosRequestConfig): Promise<IResponse<T>> => {
|
||||
try {
|
||||
const response = await service.request<IResponse<T>>(config)
|
||||
const { code, msg } = response.data
|
||||
if (code !== 1000) {
|
||||
switch (code) {
|
||||
case 401: redirectLogin()
|
||||
break
|
||||
case 402: message.error(msg)
|
||||
break
|
||||
case 403: message.error(msg)
|
||||
break
|
||||
case 405: message.error(msg)
|
||||
break
|
||||
default: message.error('系统未知错误')
|
||||
}
|
||||
return {
|
||||
code: -1,
|
||||
msg: 'error',
|
||||
data: null as any
|
||||
}
|
||||
}
|
||||
return response.data
|
||||
} catch (err: any) {
|
||||
switch (err) {
|
||||
}
|
||||
if(!window.navigator.onLine) {
|
||||
errorInfoRet('请检查网络连接')
|
||||
}
|
||||
return {
|
||||
code: -1,
|
||||
msg: 'error',
|
||||
data: null as any
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const redirectLogin = () => {
|
||||
message.warning('用户登录已过期, 即将跳转到登录页面重新登录')
|
||||
removeToken()
|
||||
window.location.href = '/login'
|
||||
}
|
||||
|
||||
const errorInfoRet = (msg: string) => {
|
||||
message.error(msg)
|
||||
return {
|
||||
code: -1,
|
||||
msg,
|
||||
data: null as any
|
||||
}
|
||||
}
|
||||
export default request
|
||||
Reference in New Issue
Block a user