首页 > 解决方案 > axios.post() 后没有响应

问题描述

嘿,我正在我的 vue 项目上开发登录系统,但问题是后端似乎没有响应。

这是后端功能:

auth.post('/login', async function (req, res) {
  
  const { email, password } = req.body;
  console.log(req);
  if(email !== "" && password !== "") {
    const account = await User.findOne({ where: { email: email} });
    if (account) {
      if (await account.validPassword(password)) {
          // Generate an access token
          const accessToken = jwt.sign({ id: account.id }, SECRET);
          const account_data =
          {
            'id':         account.id,
            'firstName':  account.firstName,
            'lastName':   account.lastName,
            'email':      account.email,
            'isAdmin':    account.isAdmin
          }
          res.send({accessToken, account_data});
      } else {
          res.status(200).json("Username or password incorrect");
      }
    } else {
        res.send('Username or password incorrect');
    }
  } else {
      res.send('Username or password incorrect');
  }
})

这是我调用动作的方法

 methods: {
    async loginUser(){
      
      let user = await this.$store.dispatch('loginUser', this.loginInfo);
      if(user.error){
        alert(user.error)
      } else {
        alert('Thank you for signing in, ' + user.firstName);
      }
    },
    
  }

这是动作:

 async loginUser({commit}, loginInfo){
      console.log(loginInfo)
      try{
        let response = await axios({
          method: 'POST',
          url: 'http://localhost:4000/api/auth/login', 
          data: loginInfo,
          headers: {
            // Overwrite Axios's automatically set Content-Type
            'Content-Type': 'application/json'
          }});
        let user = response.data;
        console.log(user);
        commit('SET_CURRENT_USER', user);
      } catch (e){
        alert(e);
        return {e}
      }
    }

console.log函数内try或函数内都catch不会被触发。

标签: vue.jsaxios

解决方案


推荐阅读