【问题标题】:Redirection handling after promise承诺后的重定向处理
【发布时间】:2019-04-11 04:48:37
【问题描述】:

我正在处理网站的认证部分,这是用户发送连接表单时调用的方法:

login() {
   this.$store.dispatch('RETRIEVE_TOKEN', {
        username: this.username,
        password: this.password,
    })
}

还有行动:

RETRIEVE_TOKEN(context, credentials) {

  return new Promise((resolve, reject) => {
    axios.post('someurl/auth', {
       email: credentials.username,
       password: credentials.password
          })

          .then(response => {
              const token = response.data.key

              localStorage.setItem('key', token)
              context.commit('retrieveToken', token)
              resolve(response)

              this.$router.push('/backoffice')
          })

          .catch(error => {
             console.log(error);
             reject(error)
          });

        })
    }

我的问题是即使用户发送了错误的密码和用户邮件,也会调用this.$router.push('/backoffice')。我不明白为什么。谁能给我解释一下?

【问题讨论】:

  • 这种情况下响应对象的内容是什么?
  • 你为什么要返回一个 Promise?
  • 承诺没有被拒绝。您需要检查 400 错误的响应并进行相应处理。
  • 只需console.log 回复并检查您得到了什么。此外,无需返回 Promise:RETRIEVE_TOKEN(context, credentials) { return axios.post('/someurl/auth', ...
  • 离题但 axios 返回一个承诺,因此您应该避免创建另一个承诺,因为这是一个 anti-pattern

标签: javascript vue.js promise axios vuex


【解决方案1】:

即使用户名和密码无效,服务器似乎也会返回 200 和一个空密钥。我们可以添加一个条件来检查令牌是否可用

RETRIEVE_TOKEN(context, credentials) {
  return axios.post('someurl/auth', {
     email: credentials.username,
     password: credentials.password
  })
  .then(response => {
    console.log(response.data) // If it not works, please show what's logged here
    const token = response.data.key

    if (token) { // check if token is valid
      localStorage.setItem('key', token)
      context.commit('retrieveToken', token)
      this.$router.push('/backoffice')
    } else {
      console.log('Token is not available')
    }
  })
  .catch(error => {
     console.log(error);
  });
}

【讨论】:

  • 非常感谢,正是我需要的!
  • 我在 Vuex 商店中似乎无法访问路由器,尽管我在 Vuex 商店中指定了import router from './router/index.js'。知道为什么吗?
  • main.js中如何设置路由器?
  • 没关系我很笨,我用 $router 而不是 router !非常感谢您的帮助,它帮助了很多!
猜你喜欢
  • 1970-01-01
  • 2022-12-05
  • 2022-01-22
  • 1970-01-01
  • 2014-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多