首页 > 解决方案 > Axios:用户在登录前尝试

问题描述

当我使用正确的电子邮件/密码发送“EnvioLogin”时,我从“/login”获得访问令牌,但之后我无法获得“/users”当我在浏览器中检查时,我得到这个:https://imgur。 com/NZFXeiJ https://imgur.com/B2DCebE

用户尝试登录后如何运行创建的挂钩?

import axios from "axios";
export default {
  name: "login",


  data() {
    return {
      showError: false,
      email: "",
      password: "",
    };
  },
     async created() {
    const response = await axios.get("api/users", {
      headers: {
        Authorization: "Bearer " + localStorage.getItem("token")
      }
    });

    console.log(response);
  },

  methods: {
    async EnvioLogin() {
      try {
        const response = await axios.post("api/auth/login", {
          email: this.email,
          password: this.password,
        });
        localStorage.setItem("token", response.data.token);
        const status = JSON.parse(response.status);
        if (status == "200") {
          console.log(response);
          this.$router.push("intermediorotas");
          this.showLogin = false;
        }
      } catch (error) {
        this.showError = true;
        setTimeout(() => {
          this.showError = false;
        }, 2000);
      }
    },
  },

标签: javascriptvue.jsaxios

解决方案


创建的钩子中的代码可以在名为的单独方法中,getUsers然后在方法中调用它EnvioLogin


import axios from "axios";
export default {
  name: "login",


  data() {
    return {
      showError: false,
      email: "",
      password: "",
    };
  },
  created() {
   this.getUsers();
  },

  methods: {
   async getUsers(){
   const response = await axios.get("api/users", {
      headers: {
        Authorization: "Bearer " + localStorage.getItem("token")
      }
    });

    console.log(response);
  },
    async EnvioLogin() {
      try {
        const response = await axios.post("api/auth/login", {
          email: this.email,
          password: this.password,
        });
        localStorage.setItem("token", response.data.token);
        const status = JSON.parse(response.status);
        if (status == "200") {
         this.getUsers();
          console.log(response);
          this.$router.push("intermediorotas");
          this.showLogin = false;
        }
      } catch (error) {
        this.showError = true;
        setTimeout(() => {
          this.showError = false;
        }, 2000);
      }
    },
  },

推荐阅读