猿问

如何在 MEVN 堆栈应用程序中从 MongoDB 返回当前用户信息

我正在尝试使用 Vue、Express、Node 和 MongoDB 构建一个基本的登录/注册应用程序。我已成功设置 Express 路由器以启用用户注册和登录,并将基本用户信息存储在 MongoDB 中。我试图在登录后将用户数据返回到屏幕。到目前为止,我已经router.get()在 Express 中设置了将所有用户的用户名返回到屏幕。但是,我想将axios.get()Vue.js 中的方法配置为仅返回登录用户的用户名,而不是存储在 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 中的 GET 路由


router.get('/', function(req, res) {

  User.find(function (err, products) {

    if (err) return next(err);

    res.json(products);

  });

});


临摹微笑
浏览 134回答 1
1回答

慕妹3242003

我假设您的用户模型具有用户名和密码字段,并且您的密码在 db 中加密。对于使用 username 查找用户,如果用户发现将 user.password 与请求正文中的加密密码进行比较。如果未找到用户或密码不匹配,我将发送400-Bad Request.const bcrypt = require("bcryptjs");router.post("/", async (req, res) => {&nbsp; const { username, password } = req.body;&nbsp; if (!(username && password))&nbsp; &nbsp; return res.status(400).json({ error: "username and password are required" });&nbsp; try {&nbsp; &nbsp; let user = await User.findOne({ username });&nbsp; &nbsp; if (!user) return res.status(400).json({ error: "invalid login" });&nbsp; &nbsp; const validPassword = await bcrypt.compare(password, user.password);&nbsp; &nbsp; if (!validPassword) return res.status(400).json({ error: "invalid login" });&nbsp; &nbsp; user.password = undefined;&nbsp; &nbsp; res.json(user);&nbsp; } catch (err) {&nbsp; &nbsp; console.log(err);&nbsp; &nbsp; return next(err);&nbsp; }});要在保存用户之前对密码进行哈希处理,您可以将此代码添加到用户模型中吗?UserSchema.pre('save', async function (next) {&nbsp; &nbsp; this.password = await bcrypt.hash(this.password, 12);&nbsp; &nbsp; next();});报名路线:router.post("/register", async (req, res) => {&nbsp; const { username, password } = req.body;&nbsp; if (!username || !password)&nbsp; &nbsp; return res.json({ success: false, msg: "Please pass username and password." });&nbsp; try {&nbsp; &nbsp; let user = await User.findOne({ username });&nbsp; &nbsp; if (user) return res.json({ success: false, msg: "Username already exists." });&nbsp; &nbsp; user = new User({ username, password });&nbsp; &nbsp; await user.save();&nbsp; &nbsp; res.json({ success: true, msg: "Successful created new user." });&nbsp; } catch (err) {&nbsp; &nbsp; console.log(err);&nbsp; &nbsp; res.json({ success: false, msg: "Something went bad" });&nbsp; }});
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答