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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
| import axios from 'axios' let isRefreshing = false
let callbacks: Function[] = [] function onAccessTokenFetched(newToken: String) { callbacks.forEach((callback) => { callback(newToken) }) callbacks = [] }
function addCallbacks(callback: Function) { callbacks.push(callback) }
const axiosInstance = axios.create({ baseURL: '/api', headers: { 'Content-Type': 'application/json' } })
axiosInstance.interceptors.request.use((config) => { const token = localStorage.getItem('access_token') if (token) { config.headers.Authorization = `Bearer ${token}` } return config })
axiosInstance.interceptors.response.use( (response) => { return response }, (error) => {
if ( (error.response.status.toString() === '401' || error.response.status.toString() === '403') && !(error.config.url === 'token/') && !(error.config.url === 'token/refresh/') ) { const config = error.response.config const retryOriginalRequest = new Promise((resolve) => { addCallbacks((newToken: String) => { config.headers.Authorization = `Bearer ${newToken}` resolve(axiosInstance.request(config)) }) }) if (!isRefreshing) { isRefreshing = true axiosInstance .post('/token/refresh/', { refresh: getRefreshToken() }) .then((response) => { const accessToken = response.data.access setAccessToken(accessToken) onAccessTokenFetched(accessToken) }) .catch(() => { removeToken() alert('登录无效/过期,请重新登录') location.href = window.location.origin }) .finally(() => { isRefreshing = false }) } return retryOriginalRequest } else { return Promise.reject(error) } } )
function setRefreshToken(token: string) { localStorage.setItem('refresh_token', token) }
function setAccessToken(token: string) { localStorage.setItem('access_token', token) }
function getRefreshToken() { return localStorage.getItem('refresh_token') || '' }
function removeToken() { localStorage.removeItem('access_token') localStorage.removeItem('refresh_token') }
async function loginByPassword(username: string, password: string): Promise<boolean> { try { const response = await axiosInstance.post('token/', { username: username, password: password }) if (response.status === 200) { setAccessToken(response.data.access) setRefreshToken(response.data.refresh) return true } return false } catch (error) { console.error(`Error occurred while logging in: ${error}`) return false } }
export { axiosInstance, loginByPassword, setRefreshToken, setAccessToken, getRefreshToken, removeToken, }
|