网站搜索

typescript - Axios 拦截器 - 如何从 vuex 存储返回响应


我有一个登录表单。当用户输入用户名/密码时,axios 拦截器会处理来自 API 的响应,无论它是好是坏。

然后响应会通过我的 vuex 存储路由,在那里设置用户凭证。

然而,当我在我的登录组件中使用 console.log 打印响应时,我实际上看不到我需要的字段,比如 data, status, headers 等等……我看到的是这个

有没有办法让我在继续登录用户之前验证我的数据是否已存储?

我现在能想到的唯一方法是使用一个 3 秒的 setTimeout,然后调用状态获取器来获取用户数据……我的意思是,这种方法有效,但我确信应该有更合适的解决方案。

登录.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
  });
};

答案#1

login 是 async 函数,这意味着它返回一个 promise,就像问题中描述的那样。

异步控制流,尤其是 promises,是有传染性的,这要求所有依赖它的调用者也必须使用 promises。注意 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');
    }
  }