我正在使用Node/Nuxt构建一个应用程序,并尝试使用nuxt/auth登录用户。注册和登录工作正常。但如果我试图获取自己的用户配置文件,我不知道如何动态地进行。
这是我的/GET用户的节点路由。现在我需要你的帮助。在const userId = x中,我手动粘贴了用户_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: '',
},
},
},发布于 2020-09-25 22:31:29
这与其说是Nuxt的做法,不如说是Node的做法,但您需要使用路由参数。
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>https://stackoverflow.com/questions/64064177
复制相似问题