如何在MEVN堆栈应用程序中从MongoDB返回当前用户信息 [英] How to return current user information from MongoDB in a MEVN stack app

查看:34
本文介绍了如何在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()方法以执行类似的操作?我的代码如下:

I am attempting to build a basic login/registration app using Vue, Express, Node, and MongoDB. I have been successful in setting up the Express router to enable registration and logging in of users, with basic user info stored in MongoDB. I am attempting to return user data back to the screen after logging in. So far, I have set up router.get() in Express to return the username of all users back to the screen. However, I want to configure the axios.get() method in Vue.js to return only the username of the logged in user, as opposed to all the user names stored in MongoDB. Normally in Firebase I would use something like let snapshot = await ref.where('userid', '==', firebase.auth().currentUser.uid).get() to send back info exclusively about the current user. How can I set up my axios.get() method to execute something similar? My code is below:

登录页面

<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中获取路线

GET route in 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.'});
    });
  }
});

推荐答案

我假设您的用户模型具有用户名和密码字段,并且您的密码已在db中加密.

I assume your user model has username and password fields, and your password is encrypted in db.

用于查找具有用户名的用户,如果用户发现将user.password与请求正文中的加密密码进行了比较.如果找不到用户,或者密码不匹配,我将发送 400-Bad Request .

For finding user with username, if user found comparing the user.password with the encrypted password in the request body. If user not found, or passwords don't match, I send 400-Bad Request.

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

要在保存用户之前对密码进行哈希处理,可以将此代码添加到用户模型中吗?

To hash the password before saving the user, can you add this code to the user model?

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

这篇关于如何在MEVN堆栈应用程序中从MongoDB返回当前用户信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆