我想知道我应该从商店中增加哪些代码,并添加到Login.vue中
以及如何将验证错误从商店中的API返回,以便在Login.vue页面中处理它们
Login.vue
<template>My login form is here</template>
<script>
import { AUTH_AUTHENTICATE } from "@/modules/auth/store/index";
methods: {
loginFormSubmit() {
/** AFTER LOGIN SUCCESS FROM STORE,
WHAT CAN I HANDLE HERE SO THAT MY STORE IS CLEAN
*/
this.$store.dispatch(AUTH_AUTHENTICATE, this.loginForm);
}
}
</script>src/modules/auth/store/index
export const AUTH_AUTHENTICATE = "/api/auth/authenticate";
actions: {
[AUTH_AUTHENTICATE]: ({ commit }, loginForm) => {
toolsApi.get("/sanctum/csrf-cookie").then(() => {
toolsApi
.post("/api/auth/authenticate", loginForm)
.then(response => {
if (response.data.status == "success") {
const token = `Bearer ${response.data.data.token}`;
Cookie.set("AUTH-TOKEN", token);
toolsApi.defaults.headers.common.Authorization = Cookie.get(
"AUTH-TOKEN"
);
commit("loginStatus", true);
this.$router.push({ name: "dashboard.index" });
}
})
.catch(error => {
console.log("Error");
console.log(error);
});
});
}
}任何关于修正我的代码的指导都会对我有很大帮助。
/****更新*/
API错误响应
{
"status": "error",
"message": "Validation errors.",
"errors": {
"email": [
"The email field is required."
],
"password": [
"The password field is required."
]
}
}在商店
toolsApi
.post("/api/auth/authenticate", loginForm)
.then(response => {
if (response.data.status == "success") {
const token = `Bearer ${response.data.data.token}`;
Cookie.set("AUTH-TOKEN", token);
toolsApi.defaults.headers.common.Authorization = Cookie.get(
"AUTH-TOKEN"
);
commit("setLoginStatus", true);
resolve(response.data.data);
// this.$router.push({ name: "dashboard.index" });
}
})
.catch(error => {
reject(error);
});发布于 2021-08-29 17:40:14
尝试从toolsApi.get(...)动作返回[AUTH_AUTHENTICATE],然后像承诺一样访问它。另一种在操作中抛出异常并在登录页面捕获异常的方法。
https://stackoverflow.com/questions/68975056
复制相似问题