我有一个登录表格。当用户输入用户名/密码时,axios拦截器会处理来自api的响应,无论响应是好是坏。
然后将响应路由到我的vuex存储,其中设置了用户凭据。
但是,当我在Login组件中进行console.log响应时,实际上并没有看到我需要的字段,例如data, status, headers
等。我看到了
在继续登录用户之前,是否可以通过某种方式验证我的数据是否在存储中?
在这一点上,我唯一想到的是使用setTimeout
3秒钟并调用状态获取器来检索用户数据。.我的意思是它可以工作,但我相信有一个更合适的解决方案在那里
Login.vue
onClickLogin() {
const userToLogin = {
username: this.loginForm.username,
password: this.loginForm.password
};
const response = UsersModule.login(userToLogin);
console.log("response", response); // returns what is pictured in the image above so the if block is technically wrong
if (response) {
this.$router.push("/");
}
}
axios请求类
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_URL,
timeout: 5000
});
service.interceptors.response.use(
response => {
return response.data;
},
error => {
Message({
message: error.message || "Error",
type: "error",
duration: 5 * 1000
});
return Promise.reject(error);
}
);
vuex用户登录功能
@Action({ rawError: true })
async login(usersSubmit: UserSubmit) {
const response: any = await loginUser(usersSubmit);
if (typeof response !== "undefined") {
const { accessToken, username, name } = response;
setToken(accessToken);
this.SET_TOKEN(accessToken);
this.SET_USERNAME(username);
this.SET_NAME(name);
}
}
从vuex商店调用axios请求的api类
export const loginUser = (data: UserSubmit) => {
return request({
url: "/auth/login",
method: "post",
data
});
};
答案 0 :(得分:2)
login
是async
函数,这意味着它会返回一个承诺,如问题所述。
异步控制流特别是Promise具有传染性,这也要求所有依赖它的调用方也使用Promise。请注意,login
不返回任何内容,因此无法解析为响应:
async onClickLogin() {
const userToLogin = {
username: this.loginForm.username,
password: this.loginForm.password
};
try {
await UsersModule.login(userToLogin);
this.$router.push("/");
} catch (err) {
console.error('Login failed');
}
}