使用 NestJs 后端在 VueJS 中获取用户信息

Get user informations in VueJS with a NestJs backend

所以我正在创建一个带有 VueJS 前端的 NestJS API。我已经使用 passportjs 序列化用户信息,您可以在下面阅读它:

@Injectable()
export class SessionSerializer extends PassportSerializer {
  serializeUser(user: any, done: (err: Error, user: any) => void): any {
    done(null, user);
  }
  deserializeUser(payload: any, done: (err: Error, payload: string) => void): any {
    done(null, payload);
  }

}

我的 API 工作正常,但我不知道如何在我的前端应用程序中检索用户数据。我的一个视图中有此代码,但我的用户对象中没有任何内容。

<script>
  import UserDataService from 'src/services/UserDataService';

  export default {
    name: 'UserProfile',
    data () {
      return {
        
      }
    },
    methods: {
      getUserData: function () {
        let self = this
       UserDataService.getUser()
          .then((response) => {
            console.log(response)
            self.$set(this, "user", response.data.user)
            console.log(response.data.user.id)
          })
          .catch((errors) => {
            console.log(errors)
          })
      }
    },
    mounted () {
      this.getUserData()
    }
  }
</script>

有关信息,我正在使用 axios。

这是我为了学习如何做而做的项目 API,我选择了 VueJS,因为显然它比 Angular 更“简单”。如果你有什么建议,我会很乐意采纳。

提前感谢您的回答。

您没有在 data 函数中初始化 user 属性。

根据文档:

Since Vue doesn’t allow dynamically adding root-level reactive properties, you have to initialize Vue instances by declaring all root-level reactive data properties upfront, even with an empty value.

你应该这样添加:

data () {
 return {
   user: {} // you may initialize it with the value that you think it's more convenient
 }
}

也不需要 let self = this,因为箭头函数已经在使用其包含块的上下文,即 getUserData 函数。

话虽如此,在这种情况下也没有必要使用 this.$set,因为这种类型的 属性 声明 反应式的(Vue.set或其本地版本 this.$set 通常用于需要更改 Vue 反应系统无法检测到的属性的情况。

你可以这样做:

getUserData: function () {
  UserDataService.getUser()
    .then((response) => {
      console.log(response)
      this.user = response.data.user
      console.log(response.data.user.id)
    })
    .catch((errors) => {
      console.log(errors)
    })
}

查看文档以获取有关 Vue 及其 reactivity system 的更多信息。