学习nodejs已经有一段时间了由于一些事情一直没有写

1.首先使用idea新建一个项目

 

 

2、创建的项目目录如下图所示 

 

 3.打开app.js,找到模版引擎设置并进行修改

 修改为如下代码

//自己修改的默认引擎
// 这里修改是为了前端可以识别html页面
app.set('views', path.join(__dirname, './views'));
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');

4.1数据库js

在routes目录下创建 db.js,此模块负责数据库的连接

//db.js
// 连接MySQL 这里需要安装驱动  如果没有安装驱动 $ cnpm install mysql
var mysql = require('mysql');
var pool = mysql.createPool({
    host: 'localhost',
    user: 'root',//用户名
    password: 'root',//密码
    database: 'school'//数据库名
});
//通用的处理方法
function query(sql, callback) {
    pool.getConnection(function (err, connection) {
        // Use the connection
        connection.query(sql, function (err, rows) {
            callback(err, rows);//回调
            connection.release();//释放链接
        });
    });
}
exports.query = query;

创建数据库表

/*
 Navicat Premium Data Transfer

 Source Server         : mysql
 Source Server Type    : MySQL
 Source Server Version : 50560
 Source Host           : localhost:3306
 Source Schema         : school

 Target Server Type    : MySQL
 Target Server Version : 50560
 File Encoding         : 65001

 Date: 23/11/2018 03:38:15
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for students
-- ----------------------------
DROP TABLE IF EXISTS `students`;
CREATE TABLE `students`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `age` int(11) NULL DEFAULT NULL,
  `adress` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 14 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of students
-- ----------------------------
INSERT INTO `students` VALUES (1, '花花', 18, '梅溪湖邱琦雯');
INSERT INTO `students` VALUES (2, '花花', 12, '上海');
INSERT INTO `students` VALUES (3, '张三', 12, '北京');
INSERT INTO `students` VALUES (4, '2qa2qa', 13, '北京');
INSERT INTO `students` VALUES (5, '花花2', 12, '111');
INSERT INTO `students` VALUES (6, '花花', 12, '北京132213');
INSERT INTO `students` VALUES (8, '2qa2qa', 12, '北京');
INSERT INTO `students` VALUES (9, '22q', 13, '北京132213');

SET FOREIGN_KEY_CHECKS = 1;

 

 

路由(就是映射地址,做过编程开发的都懂,简单举例  "/Student/getStudentById.action")

  在routes目录下创建 student.js,此模块负责映射地址的注册,简言之就相当MVC的Controller层,这里并不是传统的MVC模式,此处只做了功能实现。

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



/**
 * 查询列表页直接到页面页面上来查询a
 */
router.get('/', function (req, res, next) {
    res.render('students', {title: '学生管理', datas: []});
});


/**
 * 新增页面跳转
 */

router.post('/add', function (req, res) {
    var name = req.body.name;
    var age = req.body.age;
    var adress = req.body.adress;
    db.query("INSERT INTO school.students(name,age,adress) values('" + name + "'," + age + ",'" + adress + "')", function (err, rows) {
        if (err) {
            res.end('新增失败:' + err);
        } else {
            res.json(rows);
        }
    })
});

/**
 * 删
 */
router.post('/del', function (req, res) {
    var id = req.body.id;

    db.query("delete from students where id=" + id, function (err, rows) {
        if (err) {
            res.end('删除失败:' + err)

        } else {
            //我这里都是用的post提交且ajax返回

            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 adress = req.body.adress;
    db.query("update students set name='" + name + "',age='" + age + "',adress= '" + adress + "' where id=" + id, function (err, rows) {
        if (err) {
            res.end('修改失败:' + err);
        } else {
            //我这里都是用的post提交且ajax返回
            //res.redirect('/students');  不然用词句返回
            res.json(rows);

        }
    });
});


/**
 * 查询
 */
router.post('/search', function (req, res) {
    var name = req.body.s_name;


    var sql = "select * from students ";

    if (name) {
        sql += "  where name like '%" + name + "%' ";
    }
    console.log(sql)
    db.query(sql, function (err, rows) {
        if (err) {
            res.end("查询失败:", err)
        } else {
            res.json(rows);
        }
    });
});


module.exports = router;

视图 删除views下的.ejs文件,创建项目截图中的对应html文件,因为我不想写多个html页面在这里用了layui和vue

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><%=title%></title>
    <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>
    <link rel="stylesheet" href="javascripts/layui/css/layui.css">
    <script type="text/javascript" src="javascripts/layui/layui.js"></script>
</head>
<body>

<div id="app">
    <span id="finds">
    <div style="">
        <div style="float: left;width:10%;">
            <a class="layui-btn" data-type="add">新增</a>
        </div>
        <div style="float: right;width:90%;">
            <form action="/student/search" method="post" onsubmit="return false" id="forms">
                姓名:<input type="text" name="s_name" id="s_name" class="text"> &nbsp;&nbsp;
                <input type="submit" class="layui-btn" value="查询" @click="find()">
            </form>
        </div>
    </div>

    <table style="">
        <tr>
            <th width="10%">编号</th>
            <th width="15%">姓名</th>
            <th width="10%">年龄</th>
            <th width="50%">地址</th>
              <th width="15%">操作</th>
        </tr>
        <tr v-for="item in list">
            <td>{{item.id}}</td>
            <td>{{item.name}}</td>
            <td>{{item.age}}</td>
            <td>{{item.adress}}</td>
             <td>
                <a href="#" class="layui-btn-danger" @click="remove(item.id)">删除</a>&nbsp;&nbsp;
                 <a href="#" class="layui-btn-primary" @click="edit(item)">修改</a>
            </td>
        </tr>
    </table>
        </span>
    <div>
        <!--隐藏域-->
        <div style="margin:3px; display: none" id="box1" target="chance">
            <form class="layui-form" onsubmit="return false" id="chancefrom">
                <div class="layui-form-item">
                    <label class="layui-form-label">名字</label>

                    <input type="text" placeholder="必填项" lay-verify="required" style="width: 570px"
                           class="layui-input" id="name" name=name>

                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">年龄</label>
                    <input type="text" placeholder="必填项" lay-verify="required" style="width: 570px"
                           class="layui-input" id="age" name=age>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">地址</label>
                    <input type="text" placeholder="必填项" lay-verify="required" style="width: 570px"
                           class="layui-input" id="adress" name=adress>
                </div>
            </form>
        </div>

    </div>
</div>
<!--public文件夹-->
<script src="javascripts/jquery-3.3.1.js"></script>
<script src="javascripts/vue.js"></script>
<script>
    var vue = new Vue({
        el: '#app',
        data: {
            list: find(),
        }, methods: {
            find() {
                vue.list = find();
            },edit(item){
                $("#name").val(item.name)
                $("#age").val(item.age)
                $("#adress").val(item.adress)
                layer.open({
                    type: 1,
                    area: ['80%', '80%'],
                    fixed: false, // 不固定
                    maxmin: true,
                    shadeClose: true,
                    content: $('#box1'),
                    btn: ['确认', '取消'],
                    yes: function (index, layero) {
                        $.post("/student/update", {
                            name: $("#name").val(),
                            age: $("#age").val(), adress: $("#adress").val(),
                            id:item.id
                        }, function (msg) {
                            if (msg.affectedRows>0) {
                                layer.msg("修改成功")
                                vue.list=find();
                                layer.closeAll();
                            } else {
                                layer.msg("修改失败")
                                alert("增加失败")
                            }
                        })

                    }

                })

            }
            ,
            remove(id){
                if (confirm("确定要删除这条数据吗?")) {
                    $.post("/student/del",{id:id},function(msg){
                        if (msg.affectedRows>0) {
                            alert("删除成功")
                            vue.list = find();
                        }else{
                            alert("删除失败")
                        }
                    })
                }

            }
        }

    });
    //使用layui 渲染页面
    layui.use(['table', 'form', 'layer'], function () {
        var form = layui.form;
        var table = layui.table;
        var layer = layui.layer;

        //创建事件
        var $ = layui.$, active = {//datatype
            //新增事件
            add: function () {
                $("#name").val("")
                $("#age").val("")
                $("#adress").val("")
                layer.open({
                    type: 1,
                    area: ['80%', '80%'],
                    fixed: false, // 不固定
                    maxmin: true,
                    shadeClose: true,
                    content: $('#box1'),
                    btn: ['确认', '取消'],
                    yes: function (index, layero) {
                        $.post("/student/add", {
                            name: $("#name").val(),
                            age: $("#age").val(), adress: $("#adress").val()
                        }, function (msg) {
                            if (msg.affectedRows>0) {
                                layer.msg("增加成功")
                                vue.list=find();
                                    layer.closeAll();
                            } else {
                                layer.msg("增加失败")
                                alert("增加失败")
                            }
                        })

                    }

                })
            }

        }
//绑定事件
        $('.layui-btn').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });


    })


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


</script>


</body>
</html>

仅有上述文件,项目还是不能运行起来的,最重要的一个文件app.js,此文件事node.js服务的总配置文件,它告诉框架文件模块的加载顺序。

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var index = require('./routes/index');
var  student= require('./routes/student');

var app = express();

// 原来的模板引擎设置
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'ejs');

//自己修改的默认引擎
// 这里修改是为了前端可以识别html页面
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.use(express.static(path.join(__dirname, 'public')));
//配置一下js文件
app.use('/', index);
app.use('/student',student );



// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// 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;

 

然后启动项目访问http://localhost:3000/student就可以看到了,如果这时候有报错可能是某些模块没有 下载就好了

这里没有做太多的样式 

Logo

前往低代码交流专区

更多推荐