我正在尝试使用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.headers.common['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);
});
});
User.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcryptjs');
var UserSchema = new Schema({
username: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
}
});
UserSchema.pre('save', function (next) {
var user = this;
if (this.isModified('password') || this.isNew) {
bcrypt.genSalt(10, function (err, salt) {
if (err) {
return next(err);
}
bcrypt.hash(user.password, salt, null, function (err, hash) {
if (err) {
return next(err);
}
user.password = hash;
next();
});
});
} else {
return next();
}
});
UserSchema.methods.comparePassword = function (passw, cb) {
bcrypt.compare(passw, this.password, function (err, isMatch) {
if (err) {
return cb(err);
}
cb(null, isMatch);
});
};
module.exports = mongoose.model('User', UserSchema);
注册路线
router.post('/register', function(req, res) {
if (!req.body.username || !req.body.password) {
res.json({success: false, msg: 'Please pass username and password.'});
} else {
var newUser = new User({
username: req.body.username,
password: req.body.password
});
// save the user
newUser.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Username already exists.'});
}
res.json({success: true, msg: 'Successful created new user.'});
});
}
});
答案 0 :(得分:1)
我假设您的用户模型具有用户名和密码字段,并且您的密码已在db中加密。
用于查找具有用户名的用户,如果用户发现将user.password与请求主体中的加密密码进行了比较。 如果找不到用户,或者密码不匹配,我会发送400错误的请求。
const bcrypt = require("bcryptjs");
..
router.post('/', async (req, res) => {
const { username, password } = req.body;
if (!(username && password))
return 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 bcrypt.compare(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);
}
});
要在保存用户之前对密码进行哈希处理,可以将此代码添加到用户模型中吗?
UserSchema.pre('save', async function (next) {
this.password = await bcrypt.hash(this.password, 12);
next();
});
注册路线:
router.post('/register', async (req, res) => {
const { username, password } = req.body;
if (!username || !password)
return res.json({ success: false, msg: 'Please pass username and password.' });
try {
let user = await User.findOne({ username });
if (user) return res.json({ success: false, msg: 'Username already exists.' });
user = new User({ username, password });
await user.save();
res.json({ success: true, msg: 'Successful created new user.' });
} catch (err) {
console.log(err);
res.json({ success: false, msg: 'Something went bad' });
}
});