测试具体代码如下
import axios from 'axios'
let requestsQueue: Function[] = []
let isFreshToken = false
function getToken () {
return http.get('/api/token').then(res => {
return res.data.data.result
})
}
const getSToken = () =>{
return sessionStorage.getItem('__token__')
}
const setSToken = (token: string) =>{
return sessionStorage.setItem('__token__', token)
}
const http = axios.create({
timeout: 3000
})
http.interceptors.request.use((config)
=> {
if(config.url?.match('token')) {
return config
}
config.url = `${config.url}?t=${new Date().getTime()}`
const crsfToken = getSToken()
if(!crsfToken) {
if(!isFreshToken){
isFreshToken = true
getToken().then(token => {
setSToken(token)
requestsQueue.forEach(cb => {
cb(token)
})
requestsQueue = []
}).finally(() => {
isFreshToken = false
})
}
return new Promise(resolve => {
requestsQueue.push(token => {
config.headers['x-crsf-token'] = token
resolve(config)
})
})
}
config.headers['x-crsf-token'] = crsfToken
return config
})
http.interceptors.response.use(res =>{
return res;
})
export default http