首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Node,Nuxt,MongoDB,nuxt/auth -如何获取用户_id?

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

Stack Overflow用户
提问于 2020-09-25 20:29:36
回答 1查看 476关注 0票数 0

我正在使用Node/Nuxt构建一个应用程序,并尝试使用nuxt/auth登录用户。注册和登录工作正常。但如果我试图获取自己的用户配置文件,我不知道如何动态地进行。

这是我的/GET用户的节点路由。现在我需要你的帮助。在const userId = x中,我手动粘贴了用户_id,但我当然需要动态地使用它。像const userId = req.user这样的东西

代码语言:javascript
复制
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中的作者策略

代码语言:javascript
复制
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: '',
      },
    },

  },
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-25 22:31:29

这与其说是Nuxt的做法,不如说是Node的做法,但您需要使用路由参数。

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
<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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64064177

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档