简体   繁体   English

Node、Nuxt、MongoDB、nuxt/auth - 如何获取用户 _id?

[英]Node, Nuxt, MongoDB, nuxt/auth - How to get user _id?

I'm building an app with Node/Nuxt and try to log in user with nuxt/auth.我正在使用 Node/Nuxt 构建一个应用程序,并尝试使用 nuxt/auth 登录用户。 Signup and Login works fine.注册和登录工作正常。 But if I try to get the own user profile, I don't have an idea how to do it dynamically.但是,如果我尝试获取自己的用户配置文件,则我不知道如何动态执行此操作。

Here is my node route of /GET User.这是我的 /GET 用户节点路由。 And here I need your help.在这里我需要你的帮助。 In const userId = x I pasted the User _id manually, but I need it of course dynamically.const userId = x我手动粘贴了 User _id,但我当然需要它动态。 Something like const userId = req.user类似于const userId = req.user

router.get('/auth/user', async (req, res, next) => {
  try {
    const userId = '5f6c6f1d312bc5695641b6c2';
    console.log(userId);
    const foundUser = await User.findById(userId);
    if (!foundUser) return next(new Error('User does not exist'));
    res.status(200).json({
      data: foundUser,
    });
  } catch (error) {
    next(error);
  }
});

SCREENSHOT: Here is the userID I which I need屏幕截图:这是我需要的用户 ID

Here is my auth strategie in nuxt.config.js这是我在 nuxt.config.js 中的身份验证策略

auth: {
    strategies: {
      local: {
        endpoints: {
          login: {
            url: '/api/auth/login',
            method: 'post',
            propertyName: 'accessToken',
          },
          logout: { url: '/api/auth/logout', method: 'post' },
          user: { url: '/api/auth/user', method: 'get', propertyName: false },
        },
        tokenType: '',
      },
    },

  },

This is more a Node way of doing things than a Nuxt way of doing things, but you want to use a route paramater.这更像是一种 Node 的做事方式,而不是 Nuxt 的做事方式,但是您想要使用路由参数。

router.get('/auth/user/:id', async (req, res, next) => {
  try {
    const userId = req.params.id;
    console.log(userId);
    const foundUser = await User.findById(userId);
    if (!foundUser) return next(new Error('User does not exist'));
    res.status(200).json({
      data: foundUser,
    });
  } catch (error) {
    next(error);
  }
});

Another way to do this would be to use Nuxt's Vuex store to create a state object into which you save the user ID and the user's profile data so that it can be invoked as-needed throughout your project.另一种方法是使用 Nuxt 的Vuex 存储创建一个状态对象,您可以在其中保存用户 ID 和用户的个人资料数据,以便可以在整个项目中根据需要调用它。

store/index.js : store/index.js

export const state = () => ({
  userId: null,
  userProfile: null
})

export const mutations = {
  SET_USER_ID(state, payload) {
    state.userId = payload
  },
  SET_USER_PROFILE(state, payload) {
    state.userProfile = payload
  }
}

export const actions = {
  setUserId({ commit }, payload) {
    commit('SET_USER_ID', payload)
  },
  setUserProfile({ commit }), payload {
    commit('SET_USER_PROFILE', payload)
  }
}

user.vue : user.vue :

<template>
  <div>
    <div>The user's id is {{ userid }}.</div>
    <div>The user's profile is: {{ profile }}.</div>
  </div>
</template>

<script>
import { mapState, mapActions} from 'vuex'

export default {
  computed: {
     ...mapState([userId, userProfile])
  },
  async mounted() {
    const id = (await yourLoginFunction()).user.id
    this.setUserId(id)
    
    const profile = (await yourProfileLoader(id)).user.profileData
    this.setUserProfile(profile)
  },
  methods: {
    ...mapActions([setUserId, setProfile])
  }
}
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM