当角色为“用户”时,我不会被重定向到登录页面。我的路线中有两个 getter。一个 getter 用于检查用户是否已通过身份验证,另一个 getter 用于获取 userRole。 userRole 包含以下内容:[“user”]。当我控制台记录 getter 时,我得到了正确的值,但是当我 console.log 一个字符串时,我在控制台中没有将其视为橙色字符串值。
name: "GrantQuotes",
component: GrantQuotes,
beforeEnter: (to, from, next) => {
const authStatus = store.getters["auth/userRole"];
const myArrStr = JSON.stringify(authStatus);
const obj = JSON.parse(myArrStr);
console.log(obj);
console.log("user");
if (!store.getters["auth/authenticated"] && obj.includes("user")) {
return next({
name: "Login",
});
}
next();
},
},
我的 obj.includes("user")
也返回 true。
export default {
namespaced: true,
state: {
accessToken: null,
user: null,
roles: null,
},
getters: {
authenticated(state) {
return state.accessToken && state.user;
},
user(state) {
return state.user;
},
userRole(state) {
console.log("test");
return state.roles;
},
},
mutations: {
SET_TOKEN(state, accessToken) {
state.accessToken = accessToken;
},
SET_USER(state, data) {
state.user = data;
},
SET_ROLE(state, data) {
state.roles = data;
console.log(data, "hej");
},
},
actions: {
async register({ dispatch }, credentials) {
let response = await axios.post(
"http://localhost:3000/api/auth/signup",
credentials
);
return dispatch("attempt", response.data.accessToken);
},
async signIn({ dispatch }, credentials) {
let response = await axios.post(
"http://localhost:3000/api/auth/signin",
credentials
);
return dispatch("attempt", response.data.accessToken);
},
async attempt({ commit, state }, accessToken) {
if (accessToken) {
commit("SET_TOKEN", accessToken);
}
if (!state.accessToken) {
return;
}
try {
let response = await axios.get(
"http://localhost:3000/api/auth/userMe",
{
headers: {
"x-access-token": accessToken,
},
}
);
console.log(response.data);
commit(
"SET_ROLE",
response.data.roles.map((role) => role.name)
);
commit("SET_USER", response.data);
} catch (e) {
commit("SET_TOKEN", null);
commit("SET_USER", null);
}
},
signOut({ commit }) {
commit("SET_TOKEN", null);
commit("SET_USER", null);
},
},
};
这是我的用户对象
1. {roles: Array(1), quotes: Array(5), _id: "6089da8bd846c7e42a196ac5", username: "jon", email: "jon@gmail.com", …}
1. email: "jon@gmail.com"
2. quotes: (5) ["6089e8346dba89414317e646", "6089e8d96dba89414317e647", "608abd11462bf51a1583ab05", "60c5e89d1a6cfb0f3b16f51f", "60c62dc21a6cfb0f3b16f520"]
3. roles: Array(1)
1. 0: {_id: "607a0a5d102d2f5ad7738adf", name: "user", __v: 0}
2. length: 1
3. __proto__: Array(0)
4. username: "jon"
5. __v: 10
6. _id: "6089da8bd846c7e42a196ac5"
7. __proto__: Object