vue+mongodb+nodejs的express框架实现登录注册前台完整案例及源码(1)

在这里插入图片描述
一些错误提示
在这里插入图片描述
前台:
在这里插入图片描述在这里插入图片描述
从底往上

用的vue3脚手架

创建vue.config.js


module.exports = {
  devServer: {
    open: true, // 配置自动启动浏览器
    // host: 'localhost',
    port: '8080',
    // 设置代理 devServer.proxy 可以是一个指向开发环境 API 服务器的字符串
    proxy: {
      '/api': {
        target: 'http://localhost:3000/api', // 域名 这会告诉开发服务器将任何未知请求 (没有匹配到静态文件的请求) 代理到http://localhost:8080
        changOrigin: true, // 开启代理:在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
        pathRewrite: {
          '^/api': '' // // 替换target中的请求地址,也就是说,在请求的时候,url用'/proxy'代替'http://ip.taobao.com'
        }
      }
    }
  }

}

创建.eslintrc.js

module.exports = {
  root: true,
  env: {
    node: true
  },
  'extends': [
    'plugin:vue/essential',
    '@vue/standard'
  ],
  /* 
   下面这些rules是用来设置从插件来的规范代码的规则,使用必须去掉前缀eslint-plugin-
    主要有如下的设置规则,可以设置字符串也可以设置数字,两者效果一致
    "off" -> 0 关闭规则
    "warn" -> 1 开启警告规则
    "error" -> 2 开启错误规则
  */
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'space-before-function-paren': 0,//函数左边不要有括号
    'indent': 0, //script的缩进
    "no-unused-vars": 1, // 不能有声明后未被使用的变量或参数
  },
  parserOptions: {
    parser: 'babel-eslint'
  }
}

main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'
Vue.prototype.axios = axios
// 原生ajax、axios请求时,如果不显示的设置Content-Type,那么默认是text/plain,这时服务器就不知道怎么解析数据了,所以才只能通过获取原始数据流的方式来进行解析请求数据。
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

app.vue

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <router-view/>

    <!--<HelloWorld msg="Welcome to Your Vue.js App"/> -->
  </div>
</template>

<script>
// import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'app'
  // components: {
  //   HelloWorld
  // }
}
</script>
<style lang="stylus">
#app
  font-family 'Avenir', Helvetica, Arial, sans-serif
  -webkit-font-smoothing antialiased
  -moz-osx-font-smoothing grayscale
  text-align center
  color #2c3e50
  margin-top 60px
</style>

router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/pages/Login.vue'
import Main from '@/pages/Main.vue'
import Home from '@/pages/Home.vue'
Vue.use(Router)

export default new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'Login',
      component: Login
    }, {
      path: '/main',
      name: 'Main',
      component: Main
    }, {
      path: '/home',
      name: 'Home',
      component: Home
    }
  ]
})

pages/Home.vue

<template>
    <div>
        <h3>欢迎 {{name}}</h3>
        <a href="#" @click="quit">注销登录</a>
    </div>
</template>

<script>
/* 引入公共方法 */
// import { setCookie, getCookie, delCookie } from '../../assets/js/cookie.js'
    export default {
        data() {
            return {
                name: ''
            }
        },
        mounted() {
            /* 页面挂载获取保存的值,渲染到页面上 */
            // var username = localStorage.getItem('username')
            // this.name = JSON.parse(username)
            // /* 如果cookie不存在,则跳转到登录页 */
            // if (name === '') {
            //     this.$router.push('/')
            // }
        },
        methods: {
            quit() {
                /* 删除cookie */
                localStorage.clear()
                this.$router.push('/')
            }
        }
    }
</script>

pages/Login.vue

<template>
  <div>
    <div class="login-wrap" v-show="showLogin">
      <h3>登录</h3>
      <p v-show="showTishi">{{tishi}}</p>
      <input type="text" placeholder="请输入用户名" v-model="username">
      <input type="password" placeholder="请输入密码" v-model="password">
      <button v-on:click="login">登录</button>
      <span v-on:click="ToRegister">没有账号?马上注册</span>
    </div>

    <div class="register-wrap" v-show="showRegister">
      <h3>注册</h3>
      <p v-show="showTishi">{{tishi}}</p>
      <input type="text" placeholder="请输入用户名" v-model="newUsername">
      <input type="password" placeholder="请输入密码" v-model="newPassword">
      <input type="password" placeholder="请确认密码" v-model="renewPassword">
      <button v-on:click="register">注册</button>
      <span v-on:click="ToLogin">已有账号?马上登录</span>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      showLogin: true,
      showRegister: false,
      showTishi: false,
      tishi: '',
      username: '',
      password: '',
      newUsername: '',
      newPassword: '',
      renewPassword: ''
    }
  },
  methods: {
    login() {
      if (this.username === '' || this.password === '') {
        alert('请输入用户名或密码')
      } else {
        localStorage.setItem('password', this.password)
        localStorage.setItem('username', this.username) // JSON.stringify 将JSON转为字符串存到变量里

        const loginUrl = '/api/login'
        var params = new URLSearchParams()
        params.append('username', this.username)
        params.append('password', this.password)
        this.axios({
          method: 'post',
          url: loginUrl,
          data: params
        })
          .then(res => {
            console.log(res)
            if (res.status === 200) {
              // console.log(res.code)
              if (res.data.code === 2) {
                this.tishi = '用户名或密码错误'
                this.showTishi = true
                this.username = ''
                this.password = ''
              } else if (res.data.userInfo.username === 'admin') {
                this.$router.push('/main')
              } else {
                this.tishi = '登录成功'
                this.showTishi = true
                setTimeout(
                  function() {
                    this.$router.push({ path: 'home', query: { id: 1 } })
                  }.bind(this),
                  500
                ) // 这是1秒延迟跳转
              }
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      }
    },
    register() {
      if (this.newUsername === '' || this.newPassword === '') {
        this.tishi = '请输入用户名或密码'
        this.showTishi = true
      } else {
        const registerUrl = '/api/register'
        var params = new URLSearchParams()
        params.append('username', this.newUsername)
        params.append('password', this.newPassword)
        params.append('repassword', this.renewPassword)
        this.axios({
          method: 'post',
          url: registerUrl,
          data: params
        })
          .then(res => {
            console.log(res)
            if (res.status === 200) {
              // 注册成功,1s后跳转到登录
              if (res.data.code === 1 || res.data.code === 2) {
                this.tishi = '用户名或密码不能为空'
                this.showTishi = true
              } else if (res.data.code === 3) {
                this.tishi = '两次输入密码不一致'
                this.showTishi = true
              } else if (res.data.code === 4) {
                this.tishi = '该用户已被注册'
                this.showTishi = true
                this.username = ''
                this.password = ''
                setTimeout(
                  function() {
                    this.showRegister = false
                    this.showLogin = true
                    this.showTishi = false
                  }.bind(this),
                  1000
                ) // 这是1秒延迟跳转
              } else {
                this.tishi = '注册成功'
                this.showTishi = true
                this.username = ''
                this.password = ''
                setTimeout(
                  function() {
                    this.showRegister = false
                    this.showLogin = true
                    this.showTishi = false
                  }.bind(this),
                  1000
                ) // 这是1秒延迟跳转
              }
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      }
    },
    ToLogin() {
      this.showRegister = false
      this.showLogin = true
    },
    ToRegister() {
      this.showRegister = true
      this.showLogin = false
    }
  }
}
</script>
<style>
.login-wrap {
  text-align: center;
}
input {
  display: block;
  width: 250px;
  height: 40px;
  line-height: 40px;
  margin: 0 auto;
  margin-bottom: 10px;
  outline: none;
  border: 1px solid #888;
  padding: 10px;
  box-sizing: border-box;
}
p {
  color: red;
}
button {
  display: block;
  width: 250px;
  height: 40px;
  line-height: 40px;
  margin: 0 auto;
  border: none;
  background-color: #41b883;
  color: #fff;
  font-size: 16px;
  margin-bottom: 5px;
}
span {
  cursor: pointer;
}
span:hover {
  color: #41b883;
}
</style>

pages/Main.vue

<template>
    <div>后台管理系统</div>
</template>

参考
用户登录 https://blog.csdn.net/weixin_36185028/article/details/79719579
用户注册及数据库验证 https://blog.csdn.net/weixin_36185028/article/details/79706387

猜你喜欢

转载自blog.csdn.net/fengtingYan/article/details/88807669