学习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");
/**
/**
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
//绑定事件
$(’.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;
}
仅有上述文件,项目还是不能运行起来的,最重要的一个文件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就可以看到了,如果这时候有报错可能是某些模块没有 下载就好了