Axios:用户在登录前尝试

当我使用正确的电子邮件/密码发送“EnvioLogin”时,我从“/login”获取访问令牌,但之后我无法获取“/users”,只有在我在浏览器中检查时,我才得到:https://i . stack.imgur.com/yBJK0.jpg https://i.stack.imgur.com/bWQEG.jpg

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

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

      }

    },

  },


30秒到达战场
浏览 73回答 1
1回答

慕哥9229398

创建的钩子内的代码可以位于名为的单独方法中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);      }    },  },
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript