【发布时间】:2019-01-04 22:11:35
【问题描述】:
如果访问令牌过期,我有一个拦截器来捕获 401 错误。如果它过期,它会尝试刷新令牌以获取新的访问令牌。如果在此期间进行了任何其他调用,它们将排队等待访问令牌得到验证。
这一切都很好。然而,当使用 Axios(originalRequest) 处理队列时,最初附加的 Promise 不会被调用。请参阅下面的示例。
工作拦截器代码:
Axios.interceptors.response.use(
response => response,
(error) => {
const status = error.response ? error.response.status : null
const originalRequest = error.config
if (status === 401) {
if (!store.state.auth.isRefreshing) {
store.dispatch('auth/refresh')
}
const retryOrigReq = store.dispatch('auth/subscribe', token => {
originalRequest.headers['Authorization'] = 'Bearer ' + token
Axios(originalRequest)
})
return retryOrigReq
} else {
return Promise.reject(error)
}
}
)
刷新方法(使用刷新令牌获取新的访问令牌)
refresh ({ commit }) {
commit(types.REFRESHING, true)
Vue.$http.post('/login/refresh', {
refresh_token: store.getters['auth/refreshToken']
}).then(response => {
if (response.status === 401) {
store.dispatch('auth/reset')
store.dispatch('app/error', 'You have been logged out.')
} else {
commit(types.AUTH, {
access_token: response.data.access_token,
refresh_token: response.data.refresh_token
})
store.dispatch('auth/refreshed', response.data.access_token)
}
}).catch(() => {
store.dispatch('auth/reset')
store.dispatch('app/error', 'You have been logged out.')
})
},
auth/actions 模块中的订阅方法:
subscribe ({ commit }, request) {
commit(types.SUBSCRIBEREFRESH, request)
return request
},
以及突变:
[SUBSCRIBEREFRESH] (state, request) {
state.refreshSubscribers.push(request)
},
这是一个示例操作:
Vue.$http.get('/users/' + rootState.auth.user.id + '/tasks').then(response => {
if (response && response.data) {
commit(types.NOTIFICATIONS, response.data || [])
}
})
如果此请求被添加到队列中,因为刷新令牌必须访问新令牌,我想附加原始 then():
const retryOrigReq = store.dispatch('auth/subscribe', token => {
originalRequest.headers['Authorization'] = 'Bearer ' + token
// I would like to attache the original .then() as it contained critical functions to be called after the request was completed. Usually mutating a store etc...
Axios(originalRequest).then(//if then present attache here)
})
一旦访问令牌被刷新,请求队列就会被处理:
refreshed ({ commit }, token) {
commit(types.REFRESHING, false)
store.state.auth.refreshSubscribers.map(cb => cb(token))
commit(types.CLEARSUBSCRIBERS)
},
【问题讨论】:
-
您无法获取“原始 .then() 回调”并将它们附加到您的新请求中。相反,您需要从拦截器返回一个新结果的 Promise,以便它使用新结果解析原始 Promise。
-
我不了解 axios 或 vue 的详细信息,但会假设像
const retryOrigReq = store.dispatch('auth/subscribe').then(token => { originalRequest.headers['Authorization'] = 'Bearer ' + token; return Axios(originalRequest) });这样的东西应该这样做 -
我更新了问题以添加更多上下文。我需要找到一种方法来运行原始请求中的 then 语句。在示例中,它会更新通知存储,例如。
-
很高兴知道您的
subscribe操作是什么样的,可能会有所帮助。 -
@TimWickstrom 是的,运行这些
then回调的唯一方法是解决get(…)调用返回的承诺。 Afaics,拦截器回调的返回值提供了这种能力。
标签: javascript vue.js promise vuejs2 axios