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
| import axios from 'axios' import { getToken, setToken, getRefreshToken } from '@utils/auth'
const refreshToken = () => { return instance.post('/auth/refresh', { refresh_token: getRefreshToken() }, true) }
const instance = axios.create({ baseURL: process.env.GATSBY_API_URL, timeout: 30000, headers: { 'Content-Type': 'application/json', } })
let isRefreshing = false let requests = []
instance.interceptors.response.use(response => { return response }, error => { if (!error.response) { return Promise.reject(error) } if (error.response.status === 401 && !error.config.url.includes('/auth/refresh')) { const { config } = error if (!isRefreshing) { isRefreshing = true return refreshToken().then(res=> { const { access_token } = res.data setToken(access_token) config.headers.Authorization = `Bearer ${access_token}` requests.forEach((cb) => cb(access_token)) requests = [] return instance(config) }).catch(err => { console.log('抱歉,您的登录状态已失效,请重新登录!') return Promise.reject(err) }).finally(() => { isRefreshing = false }) } else { return new Promise(resolve => { requests.push(token => { config.headers.Authorization = `Bearer ${token}` resolve(instance(config)) }) }) } } return Promise.reject(error) })
const setHeaderToken = (isNeedToken) => { const accessToken = isNeedToken ? getToken() : null if (isNeedToken) { if (!accessToken) { console.log('不存在 access_token 则跳转回登录页') } instance.defaults.headers.common.Authorization = `Bearer ${accessToken}` } }
export const get = (url, params = {}, isNeedToken = false) => { setHeaderToken(isNeedToken) return instance({ method: 'get', url, params, }) }
export const post = (url, params = {}, isNeedToken = false) => { setHeaderToken(isNeedToken) return instance({ method: 'post', url, data: params, }) }
|