本项目是在node环境下用vue-cli3搭建
根目录下创建server文件夹,用来创建后台api接口
连接数据库:
server / db.js
module.exports = {
mysql: {
host: 'localhost',
user: 'root',
password: '1234',
database: 'mydb',
port: '3306',
multipleStatements: true //允许执行多条语句
}
}
var sql = {
user: {
login: 'select * from user where userName = ? and password = ?',
queryUserList: 'select * from user',
createUser: 'insert into user (userId, userName, password) values (?, ?, ?)'
},
book: {
queryBookList: 'select * from book',
queryById: 'select * from book where bookId = ?',
createBook: 'insert into book (bookId, bookName, press, bookDescribe) values(?, ?, ?, ?)',
delete: 'delete from book where bookId = ?'
}
}
module.exports = sql;
const bookApi = require('./api/book.js');
const userApi = require('./api/user.js');
const fs = require('fs');
const path = require('path');
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
//设置跨域请求
/*app.all('*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8");
next();
});*/
//后端api路由
app.use('/api/book', bookApi);
app.use('/api/user', userApi);
//监听端口
app.listen(3003);
console.log('success list at port : 3003...')
var models = require('../db.js');
var express = require('express');
var jwt = require('jsonwebtoken');
var uuid = require('node-uuid');
var router = express.Router();
var mysql = require('mysql');
var $sql = require('../sql.js');
//连接数据库
var conn = mysql.createConnection(models.mysql);
conn.connect();
//登录接口
router.post('/login', (req, res)=>{
var sql = $sql.user.login;
var params = req.body;
var userName = params.userName;
var password = params.password;
console.log(params);
conn.query(sql, [params.userName, params.password], function(err, result) {
var data = JSON.parse(JSON.stringify(result))
console.log('data '+data.toString()+'result '+result.toString());
if(result.length === 0) {
return res.send(JSON.stringify({ //序列化json数据
status: 1,
msg: 'no admin'
}))
} else {
let content = {
userName: params.userName
}
let secretOrPrivateKey = '_jwt'; //这是加密的Key(密钥)
let token = jwt.sign(content, secretOrPrivateKey, {
expiresIn: 60 * 60 * 1 //1小时过期
});
// res.send(resBody);
return res.send(JSON.stringify({
status: 1,
msg: 'login success',
userName: params.userName,
token: token
}))
}
})
});
//创建用户
router.post('/createUser', (req, res)=>{
var sql = $sql.user.createUser;
console.log(req);
conn.query(sql, [req.body.userId, req.body.userName, req.body.password], function(err, result) {
var data = req.body;
console.log(result);
return res.send(JSON.stringify({
status: 1,
msg: 'add success',
data: data
}))
})
});
//查询用户列表
router.get('/userList', (req, res)=>{
var sql = $sql.user.queryUserList;
var params = req.body;
console.log(params);
conn.query(sql, [], function(err, result) {
var data = JSON.parse(JSON.stringify(result))
return res.send(JSON.stringify({
status: 1,
msg: 'query success',
list: data
}))
})
});
module.exports = router;
<template>
<div class="login">
<form @submit.prevent='login'>
<div class="container">
<h2 class="title">登录 | Login</h2>
<label class="username">用户名:</label>
<input type="text" name="userName" placeholder="请输入用户名" v-model="userName"><br>
<label class="password">密码:</label>
<input type="text" name="password" placeholder="请输入密码" v-model="password"><br>
<button type="submit">Login</button>
</div>
</form>
</div>
</template>
<script>
// import Vue from 'vue'
import axios from 'axios'
import { setToken, setUserName} from '../utils/cookies.js'
export default {
data() {
return {
userName: '',
password: ''
}
},
methods: {
login() {
axios({
url: '/api/user/login',
baseURL: "http://localhost:3003",
method: 'post',
data: {
userName: this.userName,
password: this.password
}
})
.then(res=>{
const data = res.data.msg;
if(data === 'login success') {
alert('登录成功')
// this.$message({
// message: '恭喜你,登录成功',
// type: 'success'
// });
setToken(res.data.token);
setUserName(res.data.userName);
//登录成功后跳转至/Books
this.$router.push({name: 'Books',path: '/books'})
} else {
alert('密码或用户名错误')
return false;
}
}).catch(err=>{
console.log(err);
})
}
}
}
</script>
<style>
.container{
position: relative;
left: 0;
right: 0;
margin: auto;
width: 360px;
padding: 20px;
background: #cfcfcf;
height: 180px;
border-radius: 4px;
box-shadow: -1px 3px 4px 4px #afafaf;
}
.username,.password{
width: 80px;
display: inline-block;
margin-top: 10px;
line-height: 26px;
}
input{
width: 260px;
height: 26px;
margin-top: 10px;
border-radius: 4px;
outline: none;
border: none;
padding-left: 10px;
}
button{
width: 80px;
height: 28px;
background: #dfdfdf;
position: absolute;
right: 36px;
bottom: 10px;
border-radius: 4px;
}
</style>