Nodejs加Vue.js的简单增删改查

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

Nodejs加Vue.js的简单增删改查_第1张图片

话不多说,首先来看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;

前台展示页面




    
    <%= title %>
    
    
    
    


姓名:    年龄:    职业:   
编号 操作 姓名 年龄 职业
{{item.id}} 删除   修改 {{item.name}} {{item.age}} {{item.professional}}

 

你可能感兴趣的:(前端,Vue.js,Nodejs)