Error: in Vue consuming Rails Api, data received but Vue can't read

Error: in Vue consuming Rails Api, data received but Vue can't read

我有一个 rails api 连接到 VueJS 前端。我正在登录。当我输入凭据并单击登录时,将调用登录方法并在“网络”选项卡中看到响应,但 Vue 抛出错误:

login error: TypeError: Cannot read property 'auth_token' of undefined

这是在网络选项卡中看到的返回数据:

{user: {id: 1, email: "test@test.ca",…},…}
auth_token: "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MDYwNDU3ODgsImlzcyI6Imlzc3Vlcl9uYW1lIiwiYXVkIjoiY2xpZW50IiwidXNlcl9pZCI6MX0.ZLlKtsdyqS-qFwJljvDsQeBxOJyU756q38-cX6MN_2Q"
user: {id: 1, email: "test@test.ca",…}
created_at: "2020-11-10T22:37:01.775Z"
email: "test@test.ca"
id: 1
password_digest: "a$bVmG1cvMidLice0Qcn8sBu36/F1HxhY0NeHT5gRKcAoV8u5Lk5wx6"
updated_at: "2020-11-10T22:37:01.775Z"

这是我的登录方法:

   async signin () {
  try {
    console.log('base rute is: ', process.env.VUE_APP_ROOT_API)
    const response = await Api.post('users/login', {
      user: {
        email: this.email_input,
        password: this.password
      }
    })
    const loggedUser = response.data
    console.log('this is login response data: ', loggedUser)
    this.$store.commit('set_token', this.loggedUser.auth_token) [THIS IS WHERE THE ERROR IS THROWN]
    this.$store.commit('set_user', this.loggedUser.user)
    localStorage.setItem('token', this.loggedUser.auth_token)
    localStorage.setItem('user', JSON.stringify(this.loggedUser.user))
    this.$emit('authenticated', true)
  } catch (err) {
    console.log('login error: ', err)
  }
}

}

我真的不知道是什么问题。

如果它在数据中,您会调用 this.loggedUser。但是你把它设置为常量了。

async signin () {
  try {
    console.log('base rute is: ', process.env.VUE_APP_ROOT_API)
    const response = await Api.post('users/login', {
      user: {
        email: this.email_input,
        password: this.password
      }
    })
    const loggedUser = response.data
    console.log('this is login response data: ', loggedUser)
    this.$store.commit('set_token', loggedUser.auth_token) 
    this.$store.commit('set_user', loggedUser.user)
    localStorage.setItem('token', loggedUser.auth_token)
    localStorage.setItem('user', JSON.stringify(loggedUser.user))
    this.$emit('authenticated', true)
  } catch (err) {
    console.log('login error: ', err)
  }
  }