节点,Nuxt,MongoDB,nuxt / auth-如何获取用户_id?

时间:2020-09-25 12:29:36

标签: node.js mongodb authentication nuxt.js

我正在使用Node / Nuxt构建应用程序,并尝试使用nuxt / auth登录用户。注册和登录工作正常。但是,如果我尝试获取自己的用户个人资料,则不知道如何动态进行。

这是我/ GET User的节点路由。 在这里,我需要您的帮助。在const userId = x中,我手动粘贴了User _id,但是我当然需要动态地粘贴它。像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

这是我在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: '',
      },
    },

  },

1 个答案:

答案 0 :(得分:0)

与Nuxt相比,这是Node的一种方式,但是您要使用route参数。

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);
  }
});

执行此操作的另一种方法是使用Nuxt的Vuex store创建一个状态对象,在其中保存用户ID和用户的个人资料数据,以便可以在整个项目中根据需要调用它。

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

<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>