【发布时间】:2020-06-19 02:14:53
【问题描述】:
我有一个登录表单。当用户输入 username/pw 时,axios 拦截器会处理来自 api 的响应,无论是好是坏。
然后响应通过我的 vuex 存储进行路由,在该存储中设置用户凭据。
但是,当我在登录组件中 console.log 响应时,我实际上并没有看到我需要的字段,例如 data, status, headers 等。我看到了这个
在继续登录用户之前,我是否可以通过某种方式验证我的数据是否在商店中?
此时我唯一能想到的就是使用setTimeout 3 秒并调用状态获取器来检索用户数据。我的意思是它有效,但我确信那里有更合适的解决方案
登录.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 store 调用 axios 请求的 api 类
export const loginUser = (data: UserSubmit) => {
return request({
url: "/auth/login",
method: "post",
data
});
};
【问题讨论】:
标签: typescript vue.js axios vuex interceptor