我在 Vuejs v2 網站中使用以下攔截器將 firebase 令牌推送到我的節點后端。在后端,我檢測/驗證令牌,使用 uid 從資料庫中提取一些資料,然后處理任何 api 呼叫。
即使我使用Firebase onIdTokenChanged自動檢索新的 ID 令牌,有時,如果用戶已登錄,但一小時未處于活動狀態,則令牌會在不重繪 的情況下過期。現在,這沒什么大不了的——我可以簽入 axios 回應攔截器并將它們推送到登錄頁面,但這似乎很煩人,如果我可以檢測到 401 令牌已過期,請重新發送 axios 呼叫并重繪 令牌,如果他們碰巧與需要來自 API 呼叫的資料的組件進行互動,用戶甚至不會知道它發生了。所以這就是我所擁有的:
main.js
Vue.prototype.$axios.interceptors.request.use(function (config) {
const token = store.getters.getSessionToken;
config.headers.Authorization = `Bearer ${token}`;
return config;
});
Vue.prototype.$axios.interceptors.response.use((response) => {
return response }, async function (error) {
let originalRequest = error.config
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
let user = auth.currentUser;
await store.dispatch("setUser", {user: user, refresh: true}).then(() => {
const token = store.getters.getSessionToken;
Vue.prototype.$axios.defaults.headers.common['Authorization'] = 'Bearer ' token;
return Vue.prototype.$axios.request(originalRequest);
});
}
return Promise.reject(error); });
let app;
auth.onAuthStateChanged(async user => {
await store.dispatch("setUser", {user: user, refresh: false}).then(() => {
if (!app) {
app = new Vue({
router,
store,
vuetify,
render: h => h(App)
}).$mount('#app')
}
})
.catch(error => {
console.log(error);
});
});
Vuex
setUser({dispatch, commit}, {user, refresh}) {
return new Promise((resolve) => {
if(user)
{
user.getIdToken(refresh).then(token => {
commit('SET_SESSION_TOKEN', token);
this._vm.$axios.get('/api/user/session').then((response) => {
if(response.status === 200) {
commit('SET_SESSION_USER', response.data);
resolve(response);
}
})
.catch(error => {
dispatch('logout');
dispatch('setSnackbar', {
color: "error",
timeout: 4000,
text: 'Server unavailable: ' error
});
resolve();
});
})
.catch(error => {
dispatch('logout');
dispatch('setSnackbar', {
color: "error",
timeout: 4000,
text: 'Unable to verify auth token.' error
});
resolve();
});
}
else
{
console.log('running logout');
commit('SET_SESSION_USER', null);
commit('SET_SESSION_TOKEN', null);
resolve();
}
})
},
我在 vuex 中設定令牌,然后在所有 API 呼叫的攔截器中使用它。所以我在這段代碼中看到的問題是,我正在使用過期令牌向后端進行 API 呼叫。這將回傳一個 401,并且 axios 回應攔截器將其拾取并完成重繪 firebase 令牌的程序。然后,這將使用與原始配置相同的配置向后端使用更新的令牌進行新的 API 呼叫,并將其回傳給原始 API 呼叫(如下)。
This all seems to work, and I can see in dev tools/network, the response from the API call is sending back the correct data. However, it seems to be falling into the catch of the following api call/code. I get an "undefined" when trying to load the form field with response.data.server, for example. This page loads everything normally if I refresh the page (again, as it should with the normal token/loading process), so I know there aren't loading issues.
vue component (loads smtp settings into the page)
getSMTPSettings: async function() {
await this.$axios.get('/api/smtp')
.then((response) => {
this.form.server = response.data.server;
this.form.port = response.data.port;
this.form.authemail = response.data.authemail;
this.form.authpassword = response.data.authpassword;
this.form.sendemail = response.data.sendemail;
this.form.testemail = response.data.testemail;
this.form.protocol = response.data.protocol;
})
.catch(error => {
console.log(error);
});
},
I have been looking at this for a few days and I can't figure out why it won't load it. The data seems to be there. Is the timing of what I'm doing causing me issues? It doesn't appear to be a CORS problem, I am not getting any errors there.
uj5u.com熱心網友回復:
您的主要問題是將 async / await 與.then(). 您的回應攔截器沒有回傳下一個回應,因為您已經將該部分包裝在其中then()而沒有回傳外部承諾。
使用 async / await 讓事情變得簡單。
此外,設定通用標頭會破壞使用攔截器的要點。你已經有了一個請求攔截器,讓它完成它的作業
// wait for this to complete
await store.dispatch("setUser", { user, refresh: true })
// your token is now in the store and can be used by the request interceptor
// re-run the original request
return Vue.prototype.$axios.request(originalRequest)
您的商店操作也屬于顯式承諾構造反模式,可以簡化
async setUser({ dispatch, commit }, { user, refresh }) {
if(user) {
try {
const token = await user.getIdToken(refresh);
commit('SET_SESSION_TOKEN', token);
try {
const { data } = await this._vm.$axios.get('/api/user/session');
commit('SET_SESSION_USER', data);
} catch (err) {
dispatch('logout');
dispatch('setSnackbar', {
color: "error",
timeout: 4000,
text: `Server unavailable: ${err.response?.data ?? err.message}`
})
}
} catch (err) {
dispatch('logout');
dispatch('setSnackbar', {
color: "error",
timeout: 4000,
text: `Unable to verify auth token. ${error}`
})
}
} else {
console.log('running logout');
commit('SET_SESSION_USER', null);
commit('SET_SESSION_TOKEN', null);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/439748.html
