我刚开始使用 vue 和 vue 资源。在后端,我使用 laravel,我在其中处理 jwt 令牌。每次请求都会刷新令牌。到目前为止,这很好用,除了一种情况:如果我使用 vue 资源连续发送两个请求,如下所示:
//first request
Vue.http.get('/api/runs').then((response) => {
return response.json();
}, (response) => {
console.log(response);
this.$set('error', {'status' : response.status, 'error': response.statusText});
});
//second request
Vue.http.get('/api/meta').then((response) => {
return response.json();
}, (response) => {
console.log(response);
this.$set('error', {'status' : response.status, 'error': response.statusText});
});
只有第一个请求具有有效令牌。我通过拦截器设置令牌:
Vue.http.interceptors.push((request, next) => {
request.headers['Authorization'] = Auth.getAuthHeader();
request.emulateJSON = true;
next(function(response) {
if(response.headers['Authorization']) {
var token = response.headers['Authorization'];
localStorage.setItem('jwt-token', token);
}
});
});
发生这种情况是因为在拦截器可以设置新的 jwt 令牌之前,两个请求都是并行触发的。所以我的问题是,如何强制第二个请求直到第一个请求完全完成,或者如何强制拦截器等待?