问题
I have the following code from my state to handle the login request and load the incoming data to state.
export const state = {
userId: "",
token: "",
authenticated: false
};
export const getters = {};
export const actions = {
async login({ commit, dispatch }, formData) {
//codes to get data from server goes here
// incoming datas are {status: true,token: 'token123', userId: '123'}
const remainingMilliseconds = 60 * 60 * 1000;
const expiryDate = new Date(new Date().getTime() + remainingMilliseconds);
localStorage.setItem("expiryDate", expiryDate.toISOString());
dispatch("autoLogout", remainingMilliseconds);
localStorage.setItem("userId", response.data.userId);
localStorage.setItem("token", response.data.token);
commit("loadState", response.data);
return response.status;
}
};
export const mutations = {
loadState(state, data) {
state.userId = data.userId;
state.token = data.token;
state.authenticated = data.status;
}
};
Methods from my login.vue
:
middleware:'nologin'
async login() {
const status = await this.$store.dispatch("admin/login", this.form);
if (status === 200) {
this.$router.push({ path: "/dashboard" });
}
},
And my methods from layouts/default.vue
in order to save data into state when the user refreshes the page:
methods: {
loadState() {
const token = localStorage.getItem("token");
const userId = localStorage.getItem("userId");
const payload = {
status: true,
token,
userId,
};
if (token && userId) {
this.$store.commit("admin/loadState", payload);
}
},
},
mounted() {
this.loadState();
},
And I have 2 middlewares nologin.js
(prevent authenticated user from accessing login page) and auth.js
(prevent unauthenticated user to access dashboard)
nologin.js
export default function ({ store, redirect }) {
console.log(store.state.admin);
if (store.state.admin.authenticated) {
redirect("/dashboard");
}
}
auth.js
placed in dashboard.vue
export default function ({ store, redirect }) {
console.log(store.state.admin);
if (!store.state.admin.authenticated) {
redirect("/login");
}
}
Apparently this somehow works (navigating from routes) but when the user types the URL the redirect doesn't work. Is this the normal behavior of nuxt js ? Is there a way to overcome this issue ?? Here is the link to sandbox.
https://codesandbox.io/s/modest-jackson-wkfuj?file=/pages/index.vue
来源:https://stackoverflow.com/questions/64131342/redirect-authenticated-users-nuxt-js