先实现增加信息:
post参数的获取:express中接受post请求参数需要借助第三方包 body-parser
下载npm install body-parser
//引入body-parser模块
const bodyParser = require('body-parser');
//拦截所有请求,配置body-parser模块
//extended:false 方法内部使用querystring模块处理请求参数的格式,并且把参数保存在req当中
//extended:true 方法内部使用第三方模块qs处理请求参数的格式
app.use(bodyParser.urlencoded({extended:false}));
//接收请求
app.post('/add',(req,res)=>{
//接收请求参数
console.log(req.body);
})
req.body可以拿到全部的post请求参数,是一个json对象,以键值对的形式保存,键是input的name,值就是表单输入的内容,接下来只需要获取到值并且保存在MySQL数据库当中就行
通过结构赋值把需要的值拿到,然后插入到数据库,最后重定向到主页面
//接收请求
app.post('/add',(req,res)=>{
//接收请求参数
const { id, name, sex,class1}= req.body;
var addSql = 'INSERT INTO student(id,name,sex,class) VALUES(?,?,?,?)';
var addSqlParams = [id,name,sex,class1];
connection.query(addSql,addSqlParams,function (err, result) {
if(err){
console.log('[INSERT ERROR] - ',err.message);
return;
}
console.log('--------------------------INSERT----------------------------');
//console.log('INSERT ID:',result.insertId);
console.log('INSERT ID:',result);
console.log('-----------------------------------------------------------------\n\n');
});
res.redirect('/index.html');
})
删除功能的实现:
思路:点击删除按钮的时候创建一个ajax对象,发送请求del,并且携带post学号的参数,post请求参数就是学号,在创建button按钮的时候把学号赋值给button按钮的id属性,点击button按钮时vue的e.target可以获取到触发事件的对象,e.target.id就可以获取到按钮的id属性,删除完之后如果使用node的redirect重定向因为是同一个页面而不会生效,我们需要在html文件中写location.href重定向才行
代码:
init.vue
<template>
<div id="init">
<div class="div2">
<div class="div21">学号</div>
<div class="div21">姓名</div>
<div class="div21">性别</div>
<div class="div21">班级</div>
<div class="div21"></div>
<div class="div21"></div>
</div>
<div class="div3" v-for="item in people">
<div class="div31">{{item.id}}</div>
<div class="div31">{{item.name}}</div>
<div class="div31">{{item.sex}}</div>
<div class="div31">{{item.class}}</div>
<div class="div31">
<router-link to='/update'>更改</router-link>
</div>
<div class="div31">
<button @click="del" :id="item.id">删除</button>
</div>
</div>
<div class="div4">
<router-link to='/add'>增加</router-link>
</div>
</div>
</template>
<script>
export default {
data(){
return{
msg:'66',
people:[
]
}
},
mounted:function(){
var xhr = new XMLHttpRequest();
xhr.open('POST','http://localhost:3000/init');
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send();
var that = this;
xhr.onload = function(){
that.people = JSON.parse(xhr.responseText);
}
},
methods:{
del:function(e){
console.log('del'+e.target.id);
var xhr = new XMLHttpRequest();
xhr.open('POST','http://localhost:3000/del');
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send('id='+e.target.id);
location.href='http://localhost:3000/index.html'
}
}
}
</script>
<style scoped="scoped">
#init{
width: 800px;
margin: auto;
border: 1px solid transparent;
}
.div2{
width: 100%;
height: 50px;
display: flex;
}
.div21{
text-align: center;
line-height: 50px;
border: 1px solid aqua;
flex: 1;
}
.div3{
width: 100%;
height: 50px;
display: flex;
}
.div31{
border: 1px solid aqua;
text-align: center;
line-height: 50px;
flex: 1;
}
</style>
const express = require('express');
const app = express();
const path = require('path');
//引入body-parser模块
const bodyParser = require('body-parser');
//拦截所有请求,配置body-parser模块
//extended:false 方法内部使用querystring模块处理请求参数的格式,并且把参数保存在req当中
//extended:true 方法内部使用第三方模块qs处理请求参数的格式
app.use(bodyParser.urlencoded({extended:false}));
//开放静态资源访问,只需要输入文件名即可,不需要输入文件夹
app.use(express.static(path.join(__dirname,'src')));
app.all("*",function(req,res,next){
//设置允许跨域的域名,*代表允许任意域名跨域
res.header("Access-Control-Allow-Origin","*");
//允许的header类型
res.header("Access-Control-Allow-Headers","Origin,X-Requested-With,Accept,Content-type");
res.header("Access-Control-Allow-Credentials",true);
//跨域允许的请求方式
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("Content-Type","application/json;charset=utf-8")
if (req.method.toLowerCase() == 'options')
res.sendStatus(200); //让options尝试请求快速结束
else
next();
});
//引入MySQL模块
var mysql = require('mysql');
//创建MySQL的连接
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '1234',
database : 'students'
});
//连接MySQL
connection.connect();
//接收请求
app.post('/add',(req,res)=>{
//接收请求参数
const { id, name, sex,class1}= req.body;
var addSql = 'INSERT INTO student(id,name,sex,class) VALUES(?,?,?,?)';
var addSqlParams = [id,name,sex,class1];
connection.query(addSql,addSqlParams,function (err, result) {
if(err){
console.log('[INSERT ERROR] - ',err.message);
return;
}
console.log('--------------------------INSERT----------------------------');
//console.log('INSERT ID:',result.insertId);
console.log('INSERT ID:',result);
console.log('-----------------------------------------------------------------\n\n');
});
res.redirect('/index.html');
})
app.post('/update',(req,res)=>{
res.send('update');
})
app.post('/del',(req,res)=>{
const {id}=req.body;
var delSql = 'DELETE FROM student where id='+id;
//删
connection.query(delSql,function (err, result) {
if(err){
console.log('[DELETE ERROR] - ',err.message);
return;
}
console.log('--------------------------DELETE----------------------------');
console.log('DELETE affectedRows',result.affectedRows);
console.log('-----------------------------------------------------------------\n\n');
});
})
app.post('/init',(req,res)=>{
//query操作可以对数据库进行操作
connection.query('SELECT * from student', function (err, result, fields) {
if(err){
//err.message会返回错误的信息
console.log('[SELECT ERROR] - ',err.message);
return;
}
console.log('--------------------------SELECT----------------------------');
console.log(result);
res.send(result);
console.log('------------------------------------------------------------\n\n');
});
})
app.listen(3000);
修改数据思路:更改替换为<button id=“upd” @click=“upd” :id=“item.id”>更改
当点击更改按钮时,把数据保存在本地,同时也把这个数据发送给后台,在update.vue组件当中提取本地数据,给location.hash=‘/update’赋值,也会造成路由的变化。但是由于路由的组件是一加载完页面就加载了全部的路由,所以保存数据之后update组件当中的数据还是空,所以需要使用location.reload();重新刷新页面读取数据
app.js代码
var id = 0;
app.post('/server',(req,res)=>{
console.log('server');
id=req.body.id;
console.log(id);
})
app.post('/update',(req,res)=>{
console.log('update');
const {name,sex,class1}=req.body;
var modSql = 'UPDATE student SET name = ?,sex = ?,class = ? WHERE Id = ?';
var modSqlParams = [name,sex,class1,id];
//改
connection.query(modSql,modSqlParams,function (err, result) {
if(err){
console.log('[UPDATE ERROR] - ',err.message);
return;
}
console.log('--------------------------UPDATE----------------------------');
console.log('UPDATE affectedRows',result.affectedRows);
console.log('-----------------------------------------------------------------\n\n');
});
res.redirect('/index.html');
})
init.vue代码
upd:function(e){
console.log('upd');
sessionStorage.setItem('id',e.target.id);
var xhr = new XMLHttpRequest();
xhr.open('POST','http://localhost:3000/server');
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send('id='+e.target.id);
location.hash='/update';
location.reload();
}
完整代码:
app.js:
const express = require('express');
const app = express();
const path = require('path');
//引入body-parser模块
const bodyParser = require('body-parser');
//拦截所有请求,配置body-parser模块
//extended:false 方法内部使用querystring模块处理请求参数的格式,并且把参数保存在req当中
//extended:true 方法内部使用第三方模块qs处理请求参数的格式
app.use(bodyParser.urlencoded({extended:false}));
//开放静态资源访问,只需要输入文件名即可,不需要输入文件夹
app.use(express.static(path.join(__dirname,'src')));
app.all("*",function(req,res,next){
//设置允许跨域的域名,*代表允许任意域名跨域
res.header("Access-Control-Allow-Origin","*");
//允许的header类型
res.header("Access-Control-Allow-Headers","Origin,X-Requested-With,Accept,Content-type");
res.header("Access-Control-Allow-Credentials",true);
//跨域允许的请求方式
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("Content-Type","application/json;charset=utf-8")
if (req.method.toLowerCase() == 'options')
res.sendStatus(200); //让options尝试请求快速结束
else
next();
});
//引入MySQL模块
var mysql = require('mysql');
//创建MySQL的连接
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '1234',
database : 'students'
});
//连接MySQL
connection.connect();
//接收请求
app.post('/add',(req,res)=>{
//接收请求参数
const { id, name, sex,class1}= req.body;
var addSql = 'INSERT INTO student(id,name,sex,class) VALUES(?,?,?,?)';
var addSqlParams = [id,name,sex,class1];
connection.query(addSql,addSqlParams,function (err, result) {
if(err){
console.log('[INSERT ERROR] - ',err.message);
return;
}
console.log('--------------------------INSERT----------------------------');
//console.log('INSERT ID:',result.insertId);
console.log('INSERT ID:',result);
console.log('-----------------------------------------------------------------\n\n');
});
res.redirect('/index.html');
})
var id = 0;
app.post('/server',(req,res)=>{
console.log('server');
id=req.body.id;
console.log(id);
})
app.post('/update',(req,res)=>{
console.log('update');
const {name,sex,class1}=req.body;
var modSql = 'UPDATE student SET name = ?,sex = ?,class = ? WHERE Id = ?';
var modSqlParams = [name,sex,class1,id];
//改
connection.query(modSql,modSqlParams,function (err, result) {
if(err){
console.log('[UPDATE ERROR] - ',err.message);
return;
}
console.log('--------------------------UPDATE----------------------------');
console.log('UPDATE affectedRows',result.affectedRows);
console.log('-----------------------------------------------------------------\n\n');
});
res.redirect('/index.html');
})
app.post('/del',(req,res)=>{
console.log('del');
const {id}=req.body;
var delSql = 'DELETE FROM student where id='+id;
//删
connection.query(delSql,function (err, result) {
if(err){
console.log('[DELETE ERROR] - ',err.message);
return;
}
console.log('--------------------------DELETE----------------------------');
console.log('DELETE affectedRows',result.affectedRows);
console.log('-----------------------------------------------------------------\n\n');
});
})
app.post('/init',(req,res)=>{
console.log('init');
//query操作可以对数据库进行操作
connection.query('SELECT * from student', function (err, result, fields) {
if(err){
//err.message会返回错误的信息
console.log('[SELECT ERROR] - ',err.message);
return;
}
console.log('--------------------------SELECT----------------------------');
console.log(result);
console.log('------------------------------------------------------------\n\n');
res.send(result);
});
})
app.listen(3000);
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="app">
</div>
<script src="./bundle.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
app.vue
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
<script>
</script>
<style scoped="scoped">
</style>
init.vue:
<template>
<div id="init">
<div class="div2">
<div class="div21">学号</div>
<div class="div21">姓名</div>
<div class="div21">性别</div>
<div class="div21">班级</div>
<div class="div21"></div>
<div class="div21"></div>
</div>
<div class="div3" v-for="item in people">
<div class="div31">{{item.id}}</div>
<div class="div31">{{item.name}}</div>
<div class="div31">{{item.sex}}</div>
<div class="div31">{{item.class}}</div>
<div class="div31">
<button id="upd" @click="upd" :id="item.id">更改</button>
</div>
<div class="div31">
<button @click="del" :id="item.id">删除</button>
</div>
</div>
<div class="div4">
<router-link to='/add'>增加</router-link>
</div>
</div>
</template>
<script>
export default {
data(){
return{
msg:'66',
people:[
]
}
},
mounted:function(){
var xhr = new XMLHttpRequest();
xhr.open('POST','http://localhost:3000/init');
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send();
var that = this;
xhr.onload = function(){
that.people = JSON.parse(xhr.responseText);
}
},
methods:{
del:function(e){
console.log('del'+e.target.id);
var xhr = new XMLHttpRequest();
xhr.open('POST','http://localhost:3000/del');
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send('id='+e.target.id);
location.href='http://localhost:3000/index.html'
},
upd:function(e){
console.log('upd');
sessionStorage.setItem('id',e.target.id);
var xhr = new XMLHttpRequest();
xhr.open('POST','http://localhost:3000/server');
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send('id='+e.target.id);
location.hash='/update';
location.reload();
}
}
}
</script>
<style scoped="scoped">
#init{
width: 800px;
margin: auto;
border: 1px solid transparent;
}
.div2{
width: 100%;
height: 50px;
display: flex;
}
.div21{
text-align: center;
line-height: 50px;
border: 1px solid aqua;
flex: 1;
}
.div3{
width: 100%;
height: 50px;
display: flex;
}
.div31{
border: 1px solid aqua;
text-align: center;
line-height: 50px;
flex: 1;
}
</style>
router.js:
import Vue from 'vue'
import Router from 'vue-router/dist/vue-router.js'
import init from '../components/init.vue'
import app from '../components/app.vue'
import add from '../components/add.vue'
import del from '../components/del.vue'
import update from '../components/update.vue'
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
redirect:'/init'
},
{
path: '/init',
component: init
},
{
path: '/add',
name:'add',
component: add
},
{
path: '/del',
name:'del',
component: del
},
{
path: '/update',
name:'update',
component: update
},
]
})
update.vue:
<template>
<div id="update">
<form action="http://localhost:3000/update" method="post">
<div class="div1">
<div class="div11">
学号
</div>
<div class="div12">
<input type="text" name="id" placeholder="请输入学号" id="num" disabled="disabled">
</div>
</div>
<div class="div1">
<div class="div11">
姓名
</div>
<div class="div12">
<input type="text" name="name" placeholder="请输入姓名">
</div>
</div>
<div class="div1">
<div class="div11">
性别
</div>
<div class="div12">
<input type="text" name="sex" placeholder="请输入性别">
</div>
</div>
<div class="div1">
<div class="div11">
班级
</div>
<div class="div12">
<input type="text" name="class1" placeholder="请输入班级">
</div>
</div>
<br>
<button type="submit">更改</button>
</form>
</div>
</template>
<script>
window.onload=function(){
var k = sessionStorage.getItem('id');
console.log(k);
if(k){
var num = document.querySelector('#num');
num.value=k;
}
}
</script>
<style>
#update{
width: 60%;
height: 600px;
margin: auto;
border: 1px solid royalblue;
}
.div1{
margin-top: 10px;
margin-left: 10px;
}
</style>