1.创建项目
express -e
cnpm install 下载依赖
npm start 备注 (如果改端口,找 /bin/www ----3000—>你的端口号)
2.准备 项目资源
jquery bootstrap —> 放到public文件夹里
3.引入资源 (在 views/index.ejs 引入)
先引入 jquery.js (备注:因为bootstrap.js依赖 jquery.js所以先引入)
后引入 bootstrap(css,js)
4.先写 前端 添加模块
进入bootstra官网,找到响应模块,修改
form写功能 action method name(若是单选框,还要修改value)
5.定义后端接口
app.js 定义 一级路由
routes文件夹中 定义二级路由
----------------npm start--------------
6.添加 功能 业务逻辑
安装mongoose cnpm install mongoose --save
连接数据库服务器:
在app.js中:
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/数据库名称',function(err){
if(!err){
console.log('数据库服务器连接成功')
}
})
启动数据库服务器:mongod --dbpath c:/data/db --port 27017
------------npm start------------
创建 schema model模型
创建schema 文件夹 student.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var studentSchema=new Schema({
user:String,
age:String,
sex:String
},{timestamps:true})
module.exports=studentSchema;
创建model 文件夹 Student.js
var mongoose = require('mongoose');
var studentSchema=require('../schema/student.js');
var Student= mongoose.model('Student',studentSchema);
module.exports=Student;
api.js 导入集合类: var Student=require(’…/model/Student.js’)
/add 路由:
Student.create({user:req.body.user,age:req.body.age,sex:req.body.sex},function(err,data){
if(!err){
console.log('写入成功');
}
});
7.数据展示 (查询find())
views—index.ejs
<table class="table table-bordered">
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>时间</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<% for(var i in list){ %>
<tr>
<td>
<%= list[i].user %>
</td>
<td>
<%= list[i].age %>
</td>
<td>
<%= list[i].sex %>
</td>
<td>
<%= list[i].createdAt %>
</td>
<td>
<a class='btn btn-warning btn-xs' href="/del?a=<%= list[i]._id %>">删除</a>
</td>
</tr>
<% } %>
</tbody>
</table>
8.‘ / ’(根路由) 查询数据并响应到前端(routes/index.js):
var Student = require('../model/Student');
router.get('/', function(req, res, next) {
Student.find({},function(err,datas){
if(!err){
res.render('index', { list:datas });
}
})
});
9. 添加数据后 立刻显示在下方
api.js---/add--->添加成功时候
res.redirect('/')
10.删除 在index.js中
router.get('/del', function (req, res, next) {
var a = req.query.a;
Student.remove({ _id: a}, function (err, data) {
if (!err) {
res.redirect('/');
}
})
})