vue项目实现用户登录认证

本项目是在node环境下用vue-cli3搭建

根目录下创建server文件夹,用来创建后台api接口

连接数据库:
server / db.js

1module.exports = { 2 mysql: { 3 host: 'localhost', 4 user: 'root', 5 password: '1234', 6 database: 'mydb', 7 port: '3306', 8 multipleStatements: true //允许执行多条语句 9 } 10} 11 12

server / sql.js

1var sql = { 2 user: { 3 login: 'select * from user where userName = ? and password = ?', 4 queryUserList: 'select * from user', 5 createUser: 'insert into user (userId, userName, password) values (?, ?, ?)' 6 }, 7 book: { 8 queryBookList: 'select * from book', 9 queryById: 'select * from book where bookId = ?', 10 createBook: 'insert into book (bookId, bookName, press, bookDescribe) values(?, ?, ?, ?)', 11 delete: 'delete from book where bookId = ?' 12 } 13} 14 15module.exports = sql; 16 17

server / index.js

1const bookApi = require('./api/book.js'); 2const userApi = require('./api/user.js'); 3const fs = require('fs'); 4const path = require('path'); 5const bodyParser = require('body-parser'); 6const express = require('express'); 7const app = express(); 8 9app.use(bodyParser.json()); 10app.use(bodyParser.urlencoded({extended: false})); 11 12//设置跨域请求 13/*app.all('*', function (req, res, next) { 14 res.header("Access-Control-Allow-Origin", "*"); 15 res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild'); 16 res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS"); 17 res.header("X-Powered-By", ' 3.2.1') 18 res.header("Content-Type", "application/json;charset=utf-8"); 19 next(); 20});*/ 21 22//后端api路由 23app.use('/api/book', bookApi); 24app.use('/api/user', userApi); 25 26//监听端口 27app.listen(3003); 28console.log('success list at port : 3003...') 29 30

server下创建api文件夹,用来编写接口
server / api / user.js

1var models = require('../db.js'); 2var express = require('express'); 3var jwt = require('jsonwebtoken'); 4var uuid = require('node-uuid'); 5var router = express.Router(); 6var mysql = require('mysql'); 7var $sql = require('../sql.js'); 8 9//连接数据库 10var conn = mysql.createConnection(models.mysql); 11 12conn.connect(); 13 14//登录接口 15router.post('/login', (req, res)=>{ 16 var sql = $sql.user.login; 17 var params = req.body; 18 var userName = params.userName; 19 var password = params.password; 20 console.log(params); 21 conn.query(sql, [params.userName, params.password], function(err, result) { 22 var data = JSON.parse(JSON.stringify(result)) 23 console.log('data '+data.toString()+'result '+result.toString()); 24 if(result.length === 0) { 25 return res.send(JSON.stringify({ //序列化json数据 26 status: 1, 27 msg: 'no admin' 28 })) 29 } else { 30 let content = { 31 userName: params.userName 32 } 33 let secretOrPrivateKey = '_jwt'; //这是加密的Key(密钥) 34 let token = jwt.sign(content, secretOrPrivateKey, { 35 expiresIn: 60 * 60 * 1 //1小时过期 36 }); 37 // res.send(resBody); 38 return res.send(JSON.stringify({ 39 status: 1, 40 msg: 'login success', 41 userName: params.userName, 42 token: token 43 })) 44 } 45 }) 46}); 47 48//创建用户 49router.post('/createUser', (req, res)=>{ 50 var sql = $sql.user.createUser; 51 console.log(req); 52 conn.query(sql, [req.body.userId, req.body.userName, req.body.password], function(err, result) { 53 var data = req.body; 54 console.log(result); 55 return res.send(JSON.stringify({ 56 status: 1, 57 msg: 'add success', 58 data: data 59 })) 60 }) 61}); 62 63//查询用户列表 64router.get('/userList', (req, res)=>{ 65 var sql = $sql.user.queryUserList; 66 var params = req.body; 67 console.log(params); 68 conn.query(sql, [], function(err, result) { 69 var data = JSON.parse(JSON.stringify(result)) 70 return res.send(JSON.stringify({ 71 status: 1, 72 msg: 'query success', 73 list: data 74 })) 75 }) 76}); 77 78module.exports = router; 79 80

src / views / Login.vue

1<template> 2 <div class="login"> 3 <form @submit.prevent='login'> 4 <div class="container"> 5 <h2 class="title">登录 | Login</h2> 6 <label class="username">用户名:</label> 7 <input type="text" name="userName" placeholder="请输入用户名" v-model="userName"><br> 8 <label class="password">密码:</label> 9 <input type="text" name="password" placeholder="请输入密码" v-model="password"><br> 10 <button type="submit">Login</button> 11 </div> 12 </form> 13 </div> 14</template> 15<script> 16// import Vue from 'vue' 17import axios from 'axios' 18import { setToken, setUserName} from '../utils/cookies.js' 19export default { 20 data() { 21 return { 22 userName: '', 23 password: '' 24 } 25 }, 26 methods: { 27 login() { 28 axios({ 29 url: '/api/user/login', 30 baseURL: "http://localhost:3003", 31 method: 'post', 32 data: { 33 userName: this.userName, 34 password: this.password 35 } 36 }) 37 .then(res=>{ 38 const data = res.data.msg; 39 if(data === 'login success') { 40 alert('登录成功') 41 // this.$message({ 42 // message: '恭喜你,登录成功', 43 // type: 'success' 44 // }); 45 setToken(res.data.token); 46 setUserName(res.data.userName); 47 //登录成功后跳转至/Books 48 this.$router.push({name: 'Books',path: '/books'}) 49 } else { 50 alert('密码或用户名错误') 51 return false; 52 } 53 }).catch(err=>{ 54 console.log(err); 55 }) 56 } 57 } 58} 59 60</script> 61<style> 62.container{ 63 position: relative; 64 left: 0; 65 right: 0; 66 margin: auto; 67 width: 360px; 68 padding: 20px; 69 background: #cfcfcf; 70 height: 180px; 71 border-radius: 4px; 72 box-shadow: -1px 3px 4px 4px #afafaf; 73} 74.username,.password{ 75 width: 80px; 76 display: inline-block; 77 margin-top: 10px; 78 line-height: 26px; 79} 80input{ 81 width: 260px; 82 height: 26px; 83 margin-top: 10px; 84 border-radius: 4px; 85 outline: none; 86 border: none; 87 padding-left: 10px; 88} 89button{ 90 width: 80px; 91 height: 28px; 92 background: #dfdfdf; 93 position: absolute; 94 right: 36px; 95 bottom: 10px; 96 border-radius: 4px; 97} 98</style> 99 100

登录界面
Login...

代码交流 2021