用的node做的后台,数据库为mysql,数据交互和页面渲染用的vue,项目目录图:

话不多说,首先来看node项目的配置文件app.js,注释我会写在代码里

//引用模块
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var persons = require('./routes/person');
var app = express();

// view engine setup
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'ejs');

//修改后的
app.set('views', path.join(__dirname, './views'));
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');


app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());

//全局访问
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');
    if (req.method == 'OPTIONS') {
        res.send(200);
    }
    else {
        next();
    }
});
//引入public文件夹,让页面能获取到public文件夹内的文件
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/persons', persons);

app.use(express.static(__dirname));

// app.use(express.static(__dirname + '../public'));

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});



module.exports = app;

然后是连接数据库的js和路由配置

//db.js
// 连接MySQL
var mysql = require('mysql');
var pool = mysql.createPool({
    host: 'localhost',//本机
    user: 'root',//数据库帐号
    password: 'root',//密码
    database: 'test'//数据库
});

function query(sql, callback) {//执行sql
    pool.getConnection(function (err, connection) {//err为错误信息 connection为连接数据库
        // Use the connection
        connection.query(sql, function (err, rows) {//rows为执行完sql的返回的信息
            callback(err, rows);//回调
            connection.release();//释放链接
        });
    });
}
exports.query = query;

路由,可部分可以理解为页面访问的链接配置,全程用的ajax访问数据

var express = require('express');
var router = express.Router();
//引入数据库包
var db = require("./db.js");

/* GET  listing. */
// router.get('/', function(req, res, next) {
//   res.send('respond with a resource');
// });

/**
 * 查询列表页,直接访问
 */
router.get('/', function (req, res, next) {
    res.render('persons', {title: '人员管理', datas: 123});
});
/**
 * 新增页面跳转
 */

router.get('/add', function (req, res) {
    res.render('add');
});
router.post('/add', function (req, res) {
    var name = req.body.name;
    var age = req.body.age;
    var professional = req.body.professional;
    db.query("insert into person(name,age,professional) values('" + name + "'," + age + ",'" + professional + "')", function (err, rows) {
        if (err) {
            res.end('新增失败:' + err);
        } else {
            res.json(rows);//返回数据,为json格式
        }
    })
});

/**
 * 删
 */
router.post('/del', function (req, res) {
    var id = req.body.id;
    db.query("delete from person where id=" + id, function (err, rows) {
        // console.log(rows);
        if (err) {
            res.end('删除失败:' + err)
        } else {
            res.json(rows);
        }
    });
});
/**
 * 修改
 */
router.post('/update', function (req, res) {
    var id = req.body.id;
    var name = req.body.name;
    var age = req.body.age;
    var professional = req.body.professional;
    db.query("update person set name='" + name + "',age='" + age + "',professional= '" + professional + "' where id=" + id, function (err, rows) {
        if (err) {
            res.end('修改失败:' + err);
        } else {
         res.json(rows);
         console.log(rows);
        }
    });
});
/**
 * 查询
 */
router.post('/search', function (req, res) {
    var name = req.body.s_name;
    var age = req.body.s_age;
    var professional = req.body.s_professional;
    // console.log(req.body);
    var sql = "select * from person where true ";
    if (name) {
        sql += " and name like '%" + name + "%' ";
    }
    if (age) {
        sql += " and age=" + age + " ";
    }
    if (professional) {
        sql += " and name like '%" + professional + "%' ";
    }
    // sql = sql.replace("and","where");
    db.query(sql, function (err, rows) {
        if (err) {
            res.end("查询失败:", err)
        } else {
            res.json(rows);
        }
    });
});


module.exports = router;

前台展示页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><%= title %></title>
    <link rel="shortcut icon" href="#"/>
    <style>
        div {
            width: 800px;
            margin: 0 auto;
        }

        table {
            border-collapse: collapse;
            border-spacing: 0;
            width: 800px;
        }

        table tr td, table tr th {
            border-top: solid 1px #ccc;
            border-left: solid 1px #ccc;
            line-height: 40px;
            text-align: center;
        }

        table tr td:last-child, table tr th:last-child {
            border-right: solid 1px #ccc;
        }

        table tr:last-child td {
            border-bottom: solid 1px #ccc;
        }

        a {
            text-decoration: none;
            font-size: 14px;
        }

        .text {
            width: 150px;
        }
    </style>
    <!--../public/javascripts-->
    <script src="javascripts/jquery-3.3.1.js"></script>
</head>
<body>
<div id="app">
    <span id="finds">
    <div style="">
        <div style="float: left;width:10%;">
            <a href="#" @click="edit()">新增</a>
        </div>
        <div style="float: right;width:90%;">
            <form action="/persons/search" method="post" onsubmit="return false" id="forms">
                姓名:<input type="text" name="s_name" id="s_name" class="text"> &nbsp;&nbsp;
                年龄:<input type="number" name="s_age" id="s_age" class="text"> &nbsp;&nbsp;
                职业:<input type="text" name="s_professional" id="s_professional" class="text"> &nbsp;&nbsp;
                <input type="submit" value="查询" @click="find()">
            </form>
        </div>
    </div>

    <table style="">
        <tr>
            <th width="10%">编号</th>
            <th width="15%">操作</th>
            <th width="15%">姓名</th>
            <th width="10%">年龄</th>
            <th width="50%">职业</th>
        </tr>
        <tr v-for="item in list">
            <td>{{item.id}}</td>
            <td>
                <a href="#" @click="remove(item.id)">删除</a>&nbsp;&nbsp;
                <a href="#" @click="edit(item)">修改</a>
            </td>
            <td>{{item.name}}</td>
            <td>{{item.age}}</td>
            <td>{{item.professional}}</td>
        </tr>
    </table>
        </span>
    <div style="width: 800px;margin: auto; display: none" id="edit">
        <form action="/persons/add" method="post" onsubmit="return false">
            <input type="hidden" id="id" name="id">
            姓名:<input type="text" name="name" id="name">
            年龄:<input type="number" name="age" id="age">
            职业:<input type="text" name="professional" id="professional">
            <input type="button" value="提交" @click="edits()">
            <input type="button" value="返回" @click="backtrack()">
        </form>
    </div>
</div>
<script src="javascripts/vue.js"></script>
<script>
    var vue = new Vue({
        el: '#app',
        data: {
            list: find(),
        },
        methods: {
            find: function () {//查询
                this.list = find();
            }, edit: function (item) {//点击编辑
                $('#finds').hide();
                $('#edit').show();
                $('#id').val(item.id);
                $('#name').val(item.name);
                $('#age').val(item.age);
                $('#professional').val(item.professional);
            }, edits: function () {//修改和添加
                if ($('#id').val() == "" || $('#id').val() == null) {
                    add();
                } else {
                    edit();
                }
                this.list = find();
            }, remove: function (id) {//删除
                if (confirm("确定要删除这条数据吗?")) {
                    $.ajax({
                        type: "post",
                        url: "/persons/del",
                        dataType: "json",
                        data: {//传给servlet的数据,
                            id: id,
                        },
                        async: false,//加上这个ajax先执行
                        success: function (data) {
                            if (data.affectedRows>0) {
                                alert('删除成功');
                            }else{
                                alert('删除失败');
                            }
                        }
                    });
                }
                this.list = find();
            },backtrack:function () {//返回
                $('#finds').show();
                $('#edit').hide();
            }
        }
    })

    //查询
    function find() {
        var data2;
        $.ajax({
            type: "post",
            url: "/persons/search",
            dataType: "json",
            data: {//传给servlet的数据,
                s_professional: $('#s_professional').val(),
                s_name: $('#s_name').val(),
                s_age: $('#s_age').val()
            },
            async: false,//加上这个ajax先执行
            success: function (data) {
                // console.log(data);
                //返回处理的方法
                data2 = data;
            }
        });
        return data2;
    }

    //修改
    function edit() {
        $.ajax({
            type: "post",
            url: "/persons/update",
            dataType: "json",
            data: {//传给servlet的数据,
                professional: $('#professional').val(),
                name: $('#name').val(),
                age: $('#age').val(),
                id: $('#id').val(),
            },
            async: false,//加上这个ajax先执行
            success: function (data) {
                //返回处理的方法
                console.log(data);
                if (data.affectedRows > 0) {
                    alert('修改成功');
                    $('#finds').show();
                    $('#edit').hide();
                    $('#id').val("");
                    $('#name').val("");
                    $('#age').val("");
                    $('#professional').val("");
                } else {
                    alert('修改失败');
                }
            }
        });
    }

    //添加
    function add() {
        $.ajax({
            type: "post",
            url: "/persons/add",
            dataType: "json",
            data: {//传给servlet的数据,
                professional: $('#professional').val(),
                name: $('#name').val(),
                age: $('#age').val(),
                id: $('#id').val(),
            },
            async: false,//加上这个ajax先执行
            success: function (data) {
                //返回处理的方法
                if (data.affectedRows > 0) {
                    alert('添加成功');
                    $('#finds').show();
                    $('#edit').hide();
                    $('#id').val("");
                    $('#name').val("");
                    $('#age').val("");
                    $('#professional').val("");
                } else {
                    alert('添加失败');
                }
            }
        });
    }

</script>
</body>
</html>

 

Logo

前往低代码交流专区

更多推荐