简体   繁体   English

Axios:用户在登录前尝试

[英]Axios: Users attempts before Login

when i send "EnvioLogin" with the correct email / password i get the access token from "/login" but i cant get "/users" after that only before When i inspect in my browser i get this: https://imgur.com/NZFXeiJ https://imgur.com/B2DCebE当我使用正确的 email / 密码发送“EnvioLogin”时,我从“/login”获取访问令牌,但在那之后我无法获取“/users”当我在浏览器中检查时,我得到这个: https://imgur。 com/NZFXeiJ https://imgur.com/B2DCebE

How can i run created hooks after the user attempts to login?用户尝试登录后如何运行创建的挂钩?

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);
      }
    },
  },

The code inside the created hook could be in separate method named getUsers then call it in EnvioLogin method:创建的钩子中的代码可以在名为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);
      }
    },
  },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM