草庐IT

Vue+Element-ui+Express+MySQL数据库实现登录跳转功能

CherishTaoTao 2024-05-09 原文

文章目录


前言

本篇文章介绍使用vue+element-ui+express框架,结合MySQL数据库实现简单的登录跳转功能


一、前期准备

  1. node.js环境(14.17.6)
  2. npm包管理工具(8.3.0)

二、初始化vue项目

1.全局安装vue

在vscode中创建项目文件夹vue-login,在命令行中执行命令。

npm install -g vue@2.9.6

2.全局安装vue-cli脚手架

npm install -g vue-cli 

3.基于webpack初始化项目

vue init webpack project-name

安装选项:需要安装vue-router

cd project-name
npm run dev

三、引入相关库和依赖

1.安装依赖

在项目的package.json文件中找到“dependencies”:

加入以下依赖:

    "axios": "^0.24.0",
    "element-ui": "^2.15.6",
    "express": "^4.17.1",
    "mysql": "^2.18.1",
    "scss": "^0.2.4"

命令行输入:npm install ,安装依赖。

2.引入相关依赖

在main.js中引入相关依赖:

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import SIdentify from './components/Identify'; //自定义组件
import axios from 'axios'
Vue.component("SIdentify", SIdentify);// 验证码

window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'

Vue.prototype.$http = axios    //全局注册,使用方法:this.$http
Vue.use(ElementUI)

四、创建组件

1.Login.vue

1.在src的component下创建登录页Login.vue

<template>
  <div id="img">
    <div class="ms-title">实验室环境监测系统</div>
    <div class="ms-login">
      <div class="login">
        <!-- <h3 style="text-align: center;">登录界面</h3> -->
        <el-form :model="ruleForm"
                 :rules="rules"
                 ref="ruleForm"
                 class="demo-ruleForm">
          <el-form-item prop="userName">
            <el-input placeholder="请输入账号"
                      v-model="ruleForm.userName"
                      autocomplete="off"
                      clearable>
            </el-input>
          </el-form-item><br>
          <el-form-item prop="password">
            <el-input placeholder="请输入密码"
                      type="password"
                      v-model="ruleForm.password"
                      autocomplete="off"
                      show-password
                      clearable></el-input>
          </el-form-item><br>
          <el-form-item prop="validateCode">
            <el-input v-model="ruleForm.validateCode"
                      class="validate-code"
                      placeholder="验证码"></el-input>
            <div class="code"
                 @click="refreshCode">
              <s-identify :identifyCode="identifyCode"></s-identify>
            </div>
          </el-form-item><br>
          <div class="site">
            <el-form-item>
              <el-button type="primary"
                         @click="submitForm('ruleForm')">登陆</el-button>
              <el-button @click="resetForm('ruleForm')">重置</el-button>
              <el-button @click="registForm('ruleForm')">注册</el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>
    <div id="master">
      <!-- 2022-04-20 21:30:48 底部备案号查询(仅进行域名备案,官方代码) -->
      <!-- <a href="https://beian.miit.gov.cn/"><center>闽ICP备2021016906</center></a> -->
      <div style="width:300px;margin:0 auto; padding:20px 0;margin-left:-150px;">
        <a target="_blank"
           href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=41102402000277"
           style="display:inline-block;text-decoration:none;height:20px;line-height:20px;">
          <p style="float:left;height:20px;line-height:20px;margin: 0px 0px 0px 5px; color:#939393;">闽ICP备2021016906</p>
        </a>
      </div>

    </div>

  </div>
</template>
 
<script>
import axios from 'axios'
export default {
  name: 'login',
  data() {
    var validateAccount = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('账号不能为空'))
      } else {
        callback()
      }
    }
    var validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    var validateCode = (rule, value, callback) => {
      if (value !== this.identifyCode) {
        callback(new Error('请输入正确的验证码'))
      } else {
        callback()
      }
    }

    return {
      identifyCodes: '1234567890',
      identifyCode: '',
      ruleForm: {
        userName: '',
        password: '',
        validateCode: '',
      },
      rules: {
        userName: [
          {
            validator: validateAccount,
            trigger: 'blur',
          },
        ],
        password: [
          {
            validator: validatePassword,
            trigger: 'blur',
          },
        ],
        validateCode: [
          {
            // required: true,
            // message: '请输入验证码',
            validator: validateCode,
            trigger: 'blur',
          },
        ],
      },
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          sessionStorage.setItem('ms_username', this.ruleForm.userName)
          // alert('submit!');
          axios
            .get('/api/user/login', {
              params: {
                userName: this.ruleForm.userName,
                password: this.ruleForm.password,
              },
            })
            .then((res) => {
              console.log(res)
              if (res.data.state == 1) {
                // replace代替push,防止回退
                this.$router.replace({ path: '/second' })
                // window.location.reload()
                this.$message({
                  message: '登陆成功',
                  type: 'success',
                })
              } else if (res.data.state !== 1) {
                //this.$router.push({path: '/login'})
                this.$message({
                  message: '账号或密码错误,请重新输入',
                  type: 'error',
                })
              }
            })
        }
        //否则
        else {
          this.$message.error('登录失败')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    registForm() {
      this.$router.push('/register')
    },
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min)
    },
    refreshCode() {
      this.identifyCode = ''
      this.makeCode(this.identifyCodes, 4)
    },
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identifyCode +=
          this.identifyCodes[this.randomNum(0, this.identifyCodes.length)]
      }
      console.log(this.identifyCode)
    },
  },
  mounted() {
    this.identifyCode = ''
    this.makeCode(this.identifyCodes, 4)
  },
  beforeDestroy() {
    document.querySelector('body').removeAttribute('style')
  },
}
</script>
 
<style scoped>
#master {
  position: absolute;

  left: 50%;

  bottom: 0;

  text-align: center;
}
#img {
  /* background: url('./img4.jpeg'); */
  /* background: url('./img41.jpg'); */

  width: 100%;
  height: 100%;
  position: fixed;
  background-size: 100% 100%;
}
.login-info >>> .el-col {
  background-color: #e5e8ec;
  padding: 2% 5% 0% 2%;
}
.ms-title {
  position: absolute;
  top: 50%;
  width: 100%;
  margin-top: -240px;
  text-align: center;
  font-size: 30px;
  color: #108bf0d4;
}
.login {
  margin-top: 100px;
}
.ms-login {
  position: absolute;
  left: 50%;
  top: 50%;
  width: 300px;
  height: 400px;
  margin: -280px 0 0 -190px;
  padding: 40px;
  border-radius: 22px;
  background: hsl(204, 20%, 95%);
  box-shadow: #78a1bb 0px 0px 15px;
  opacity: 0.7;
}
.code {
  width: 112px;
  height: 35px;
  border: 1px solid #ccc;
  float: right;
  border-radius: 2px;
}
.validate-code {
  width: 136px;
  float: left;
}
.register {
  font-size: 14px;
  line-height: 30px;
  color: #999;
  cursor: pointer;
  float: right;
}
.site {
  position: relative;
  display: flex;
  justify-content: space-around;
}
el-input {
  width: 100px;
}

/* .login-info >>> .el-form-item{
  width:63%;
} */
</style>

2.验证码Identify组件:

<template>
  <div class="s-canvas">
    <canvas id="s-canvas" :width="contentWidth" :height="contentHeight"></canvas>
  </div>
</template>
<script>
  export default{
    name: 'SIdentify',
    props: {
      identifyCode: {
        type: String,
        default: '1234'
      },
      fontSizeMin: {
        type: Number,
        default: 16
      },
      fontSizeMax: {
        type: Number,
        default: 40
      },
      backgroundColorMin: {
        type: Number,
        default: 180
      },
      backgroundColorMax: {
        type: Number,
        default: 240
      },
      colorMin: {
        type: Number,
        default: 50
      },
      colorMax: {
        type: Number,
        default: 160
      },
      lineColorMin: {
        type: Number,
        default: 40
      },
      lineColorMax: {
        type: Number,
        default: 180
      },
      dotColorMin: {
        type: Number,
        default: 0
      },
      dotColorMax: {
        type: Number,
        default: 255
      },
      contentWidth: {
        type: Number,
        default: 112
      },
      contentHeight: {
        type: Number,
        default: 38
      }
    },
    methods: {
      // 生成一个随机数
      randomNum (min, max) {
        return Math.floor(Math.random() * (max - min) + min)
      },
      // 生成一个随机的颜色
      randomColor (min, max) {
        let r = this.randomNum(min, max)
        let g = this.randomNum(min, max)
        let b = this.randomNum(min, max)
        return 'rgb(' + r + ',' + g + ',' + b + ')'
      },
      drawPic () {
        let canvas = document.getElementById('s-canvas')
        let ctx = canvas.getContext('2d')
        ctx.textBaseline = 'bottom'
        // 绘制背景
        ctx.fillStyle = this.randomColor(this.backgroundColorMin, this.backgroundColorMax)
        ctx.fillRect(0, 0, this.contentWidth, this.contentHeight)
        // 绘制文字
        for (let i = 0; i < this.identifyCode.length; i++) {
          this.drawText(ctx, this.identifyCode[i], i)
        }
        this.drawLine(ctx)
        this.drawDot(ctx)
      },
      drawText (ctx, txt, i) {
        ctx.fillStyle = this.randomColor(this.colorMin, this.colorMax)
        ctx.font = this.randomNum(this.fontSizeMin, this.fontSizeMax) + 'px SimHei'
        let x = (i + 1) * (this.contentWidth / (this.identifyCode.length + 1))
        let y = this.randomNum(this.fontSizeMax, this.contentHeight - 5)
        var deg = this.randomNum(-45, 45)
        // 修改坐标原点和旋转角度
        ctx.translate(x, y)
        ctx.rotate(deg * Math.PI / 180)
        ctx.fillText(txt, 0, 0)
        // 恢复坐标原点和旋转角度
        ctx.rotate(-deg * Math.PI / 180)
        ctx.translate(-x, -y)
      },
      drawLine (ctx) {
        // 绘制干扰线
        for (let i = 0; i < 8; i++) {
          ctx.strokeStyle = this.randomColor(this.lineColorMin, this.lineColorMax)
          ctx.beginPath()
          ctx.moveTo(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight))
          ctx.lineTo(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight))
          ctx.stroke()
        }
      },
      drawDot (ctx) {
        // 绘制干扰点
        for (let i = 0; i < 100; i++) {
          ctx.fillStyle = this.randomColor(0, 255)
          ctx.beginPath()
          ctx.arc(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight), 1, 0, 2 * Math.PI)
          ctx.fill()
        }
      }
    },
    watch: {
      identifyCode () {
        this.drawPic()
      }
    },
    mounted () {
      this.drawPic()
    }
  }
</script>

3.router的index.js中引入组件

import HelloWorld from '@/components/HelloWorld'
import Login from '@/components/Login'

4.修改路由跳转

mode:'history',
  routes: [
    {
      path: '/',
      name: 'Login',
      component: Login
    },
    {
      path:'/second',
      name:'HelloWorld',
      component:HelloWorld
    }
  ]

5.创建后端服务

1.项目根目录下创建server文件夹
2.server下创建api文件夹,创建userApi.js文件:

// express框架编写各类接口。
// 包括登录注册、用户查询、历史数据查询、删除户、修改密码等

const express = require('express');
const router = express.Router();
const DBHelper = require('../utils/DBHelper');


// 验证用户名和密码
router.get('/login', (req, res) => {
  // let params = req.body;
  // 定义查询的信息为前端请求带过来的参数。
  var userName = req.query.userName;
  var password = req.query.password;
  var sqlStr = "select * from user where userName='" + userName + "' and password='" + password + "'";
  var conn = new DBHelper().getConn();

  conn.query(sqlStr, (err, result) => {

    let state = {}
    if (result.length != 0) {
      state.state = 1;
      res.json(state);
      res.end()
    } else {
      state.state = 0;
      res.json(state);
      console.log(result)
    }
  });

});
module.exports = router;

3.server文件夹下创建utils文件夹,utils中创建数据库连接文件DBHelper.js:

// 数据库配置参数,连接阿里云服务器数据库,用户名密码等。
// 数据库连接助手
const mysql = require('mysql');

class DBHelper{
    // 获取数据库连接
    getConn(){
        let conn = mysql.createConnection({
            // 数据库连接配置
            // 新建数据库连接时的 主机名或ID地址 内容
            host: '',      //服务器名或ip
            user: 'cherish', 
            database: 'user',      // 数据库名
            password: 'Qaz123plm',   // root 密码
            port: '3306',
            // 设置以字符换的形式展示。不会出现时区少8小时问题。
            dateStrings:true
        });
        conn.connect();
        return conn;
    }
}
module.exports = DBHelper;

4.server目录下创建index.js

// node后端服务器
const http = require('http');
const badyParser = require('body-parser');
const express = require('express');
const userApi = require('./api/userApi');
const DBHelper = require('./utils/DBHelper');

let conn = new DBHelper().getConn();

let app = express();
let server = http.createServer(app);

app.use(badyParser.json());
app.use(badyParser.urlencoded({
    extended: false
}));
// 后端api路由
app.use('/api/user', userApi);
server.listen(3000, () => {
    console.log(' success!! ')
})

5.数据库结构:

五、解决跨域问题

1.找到项目的config文件夹下的index.js文件
2.配置dev中的proxyTable:

    proxyTable: {
      '/api': {
        target: 'http://127.0.0.1:3000/api/',
        changeOrigin: true,    
        pathRewrite: {//路径重写
          '^/api': ''
        }
      }
    }

六、验证登录

1.运行项目

npm run dev

2.验证登录

浏览器访问:

3.登陆跳转成功

总结

1.至此,vue中结合MySQL数据库的验证登录跳转的功能成功实现。
2.不足之处多多指正。

有关Vue+Element-ui+Express+MySQL数据库实现登录跳转功能的更多相关文章

  1. ruby - i18n Assets 管理/翻译 UI - 2

    我正在使用i18n从头开始​​构建一个多语言网络应用程序,虽然我自己可以处理一大堆yml文件,但我说的语言(非常)有限,最终我想寻求外部帮助帮助。我想知道这里是否有人在使用UI插件/gem(与django上的django-rosetta不同)来处理多个翻译器,其中一些翻译器不愿意或无法处理存储库中的100多个文件,处理语言数据。谢谢&问候,安德拉斯(如果您已经在ruby​​onrails-talk上遇到了这个问题,我们深表歉意) 最佳答案 有一个rails3branchofthetolkgem在github上。您可以通过在Gemfi

  2. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  3. ruby - 如何根据特征实现 FactoryGirl 的条件行为 - 2

    我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden

  4. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

  5. ruby-on-rails - 如何在 Ruby on Rails 中实现由 JSF 2.0 (Primefaces) 驱动的 UI 魔法 - 2

    按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visitthehelpcenter指导。关闭10年前。问题1)我想知道ruby​​onrails是否有功能类似于primefaces的gem。我问的原因是如果您使用primefaces(http://www.primefaces.org/showcase-labs/ui/home.jsf),开发人员无需担心javascript或jquery的东西。据我所知,JSF是一个规范,基于规范的各种可用实现,prim

  6. ruby - 我如何添加二进制数据来遏制 POST - 2

    我正在尝试使用Curbgem执行以下POST以解析云curl-XPOST\-H"X-Parse-Application-Id:PARSE_APP_ID"\-H"X-Parse-REST-API-Key:PARSE_API_KEY"\-H"Content-Type:image/jpeg"\--data-binary'@myPicture.jpg'\https://api.parse.com/1/files/pic.jpg用这个:curl=Curl::Easy.new("https://api.parse.com/1/files/lion.jpg")curl.multipart_form_

  7. 世界前沿3D开发引擎HOOPS全面讲解——集3D数据读取、3D图形渲染、3D数据发布于一体的全新3D应用开发工具 - 2

    无论您是想搭建桌面端、WEB端或者移动端APP应用,HOOPSPlatform组件都可以为您提供弹性的3D集成架构,同时,由工业领域3D技术专家组成的HOOPS技术团队也能为您提供技术支持服务。如果您的客户期望有一种在多个平台(桌面/WEB/APP,而且某些客户端是“瘦”客户端)快速、方便地将数据接入到3D应用系统的解决方案,并且当访问数据时,在各个平台上的性能和用户体验保持一致,HOOPSPlatform将帮助您完成。利用HOOPSPlatform,您可以开发在任何环境下的3D基础应用架构。HOOPSPlatform可以帮您打造3D创新型产品,HOOPSSDK包含的技术有:快速且准确的CAD

  8. 华为OD机试用Python实现 -【明明的随机数】 2023Q1A - 2

    华为OD机试题本篇题目:明明的随机数题目输入描述输出描述:示例1输入输出说明代码编写思路最近更新的博客华为od2023|什么是华为od,od薪资待遇,od机试题清单华为OD机试真题大全,用Python解华为机试题|机试宝典【华为OD机试】全流程解析+经验分享,题型分享,防作弊指南华为o

  9. FOHEART H1数据手套驱动Optitrack光学动捕双手运动(Unity3D) - 2

    本教程将在Unity3D中混合Optitrack与数据手套的数据流,在人体运动的基础上,添加双手手指部分的运动。双手手背的角度仍由Optitrack提供,数据手套提供双手手指的角度。 01  客户端软件分别安装MotiveBody与MotionVenus并校准人体与数据手套。MotiveBodyMotionVenus数据手套使用、校准流程参照:https://gitee.com/foheart_1/foheart-h1-data-summary.git02  数据转发打开MotiveBody软件的Streaming,开始向Unity3D广播数据;MotionVenus中设置->选项选择Unit

  10. 使用canal同步MySQL数据到ES - 2

    文章目录一、概述简介原理模块二、配置Mysql使用版本环境要求1.操作系统2.mysql要求三、配置canal-server离线下载在线下载上传解压修改配置单机配置集群配置分库分表配置1.修改全局配置2.实例配置垂直分库水平分库3.修改group-instance.xml4.启动监听四、配置canal-adapter1修改启动配置2配置映射文件3启动ES数据同步查询所有订阅同步数据同步开关启动4.验证五、配置canal-admin一、概述简介canal是Alibaba旗下的一款开源项目,Java开发。基于数据库增量日志解析,提供增量数据订阅&消费。Git地址:https://github.co

随机推荐