如何在MEVN堆栈应用程序中从MongoDB返回当前用户信息
我正在尝试使用Vue,Express,Node和MongoDB构建基本的登录/注册应用程序。我已成功设置Express路由器以启用用户注册和登录,并将基本用户信息存储在MongoDB中。我试图在登录后将用户数据返回到屏幕。到目前为止,我已经在Express中设置了router.get()
,以将所有用户的用户名返回到屏幕。但是,我想在Vue.js中配置axios.get()
方法,使其仅返回已登录用户的用户名,而不是存储在MongoDB中的所有用户名。通常在Firebase中,我会使用let snapshot = await ref.where('userid', '==', firebase.auth().currentUser.uid).get()
之类的内容专门发送回有关当前用户的信息。如何设置我的axios.get()
方法以执行类似的操作?我的代码如下:
登录页面
<template>
<b-row>
<b-col cols="12">
<h2>
You are now logged in!
<b-link @click="logout()">(Logout)</b-link>
</h2>
<table style="width:100%">
<tr>
<th>User Names</th>
</tr>
<tr v-for="user in users" :key="user._id">
<td>{{ user.username }}</td>
</tr>
</table>
<ul v-if="errors && errors.length">
<li v-for="error of errors" :key="error._id">
<b-alert show>{{error.message}}</b-alert>
</li>
</ul>
</b-col>
</b-row>
</template>
<script>
import axios from 'axios'
export default {
name: 'BookList',
data () {
return {
users: [],
errors: []
}
},
created () {
axios.defaults.headersmon['Authorization'] = localStorage.getItem('jwtToken')
axios.get(`http://localhost:3000/api/auth`)
.then(response => {
this.users = response.data
})
},
methods: {
logout () {
localStorage.removeItem('jwtToken')
this.$router.push({
name: 'Login'
})
}
}
}
</script>
在Express中获取路线
router.get('/', function(req, res) {
User.find(function (err, products) {
if (err) return next(err);
res.json(products);
});
});
回答如下:我假设您的用户模型具有用户名和密码字段,并且您的密码已在db中加密。
用于查找具有用户名的用户,如果用户发现将user.password与请求正文中的加密密码进行了比较。如果找不到用户,或者密码不匹配,我将发送400错误请求。
router.post('/', async (req, res) => {
const { username, password } = req.body;
if (!(username && password))
res.status(400).json({ error: "username and password are required" });
try {
let user = await User.findOne({ username });
if (!user) return res.status(400).json({ error: "invalid login" });
const validPassword = await bcryptpare(password, user.password);
if (!validPassword) return res.status(400).json({ error: "invalid login" });
user.password = undefined;
res.json(user);
} catch (err) {
console.log(err);
return next(err);
}
});
如何在MEVN堆栈应用程序中从MongoDB返回当前用户信息
我正在尝试使用Vue,Express,Node和MongoDB构建基本的登录/注册应用程序。我已成功设置Express路由器以启用用户注册和登录,并将基本用户信息存储在MongoDB中。我试图在登录后将用户数据返回到屏幕。到目前为止,我已经在Express中设置了router.get()
,以将所有用户的用户名返回到屏幕。但是,我想在Vue.js中配置axios.get()
方法,使其仅返回已登录用户的用户名,而不是存储在MongoDB中的所有用户名。通常在Firebase中,我会使用let snapshot = await ref.where('userid', '==', firebase.auth().currentUser.uid).get()
之类的内容专门发送回有关当前用户的信息。如何设置我的axios.get()
方法以执行类似的操作?我的代码如下:
登录页面
<template>
<b-row>
<b-col cols="12">
<h2>
You are now logged in!
<b-link @click="logout()">(Logout)</b-link>
</h2>
<table style="width:100%">
<tr>
<th>User Names</th>
</tr>
<tr v-for="user in users" :key="user._id">
<td>{{ user.username }}</td>
</tr>
</table>
<ul v-if="errors && errors.length">
<li v-for="error of errors" :key="error._id">
<b-alert show>{{error.message}}</b-alert>
</li>
</ul>
</b-col>
</b-row>
</template>
<script>
import axios from 'axios'
export default {
name: 'BookList',
data () {
return {
users: [],
errors: []
}
},
created () {
axios.defaults.headersmon['Authorization'] = localStorage.getItem('jwtToken')
axios.get(`http://localhost:3000/api/auth`)
.then(response => {
this.users = response.data
})
},
methods: {
logout () {
localStorage.removeItem('jwtToken')
this.$router.push({
name: 'Login'
})
}
}
}
</script>
在Express中获取路线
router.get('/', function(req, res) {
User.find(function (err, products) {
if (err) return next(err);
res.json(products);
});
});
回答如下:我假设您的用户模型具有用户名和密码字段,并且您的密码已在db中加密。
用于查找具有用户名的用户,如果用户发现将user.password与请求正文中的加密密码进行了比较。如果找不到用户,或者密码不匹配,我将发送400错误请求。
router.post('/', async (req, res) => {
const { username, password } = req.body;
if (!(username && password))
res.status(400).json({ error: "username and password are required" });
try {
let user = await User.findOne({ username });
if (!user) return res.status(400).json({ error: "invalid login" });
const validPassword = await bcryptpare(password, user.password);
if (!validPassword) return res.status(400).json({ error: "invalid login" });
user.password = undefined;
res.json(user);
} catch (err) {
console.log(err);
return next(err);
}
});