Node学习-04-Express
Express安装
npm install express --save
Express基本认知
Hello World
// 1. 引入
const express = require('express');
// 2. 创建服务器应用程序
// 也就是原来的http.createServer
const app = express()
// 公开指定目录
// 只要这样做了,就可以直接通过/public/xxx 的方式访问 public目录中的所有资源了
app.use('/public/', express.static('./public/'));
// 当服务器收到get请求 / 的时候,执行回调函数
app.get('/', function(request, response) {
response.send('hello express');
})
app.get('/about', function(request, response) {
response.send('This is about');
})
app.listen(3000, function() {
console.log('app is running at port 3000.')
});
修改完代码之后自动重启-nodemon
安装
npm install -g nodemon
使用
// 使用 nodemon替代node命令
nodemon app.js
静态资源服务
// 公开指定目录
// 只要这样做了,就可以直接通过/public/xxx 的方式访问 public目录中的所有资源了
// 当以 /public/ 开头的时候,去 ./public/ 目录中找对应的资源
// 推荐方式
app.use('/public/', express.static('./public/'));
// 当省略第一个参数的时候,则可以通过省略 /public 的方式来访问
app.use(express.static('./public/'));
express中使用art-template
安装
npm install --save art-template
npm install --save express-art-template
配置
// 配置使用art-template模板引擎
// 第一个参数表示,当渲染以.art结尾的文件的时候,使用art-template模板引擎
// express-art-template是专门用来在express中把art-template整合到Express中
app.engine('art', require('express-art-template'));
// express为response相应对象提供了一个方法:render
// render方法默认是不可以使用,但是如果配置了模板引擎就可以使用了
// res.render('html模板名', {模板数据})
// 第一个参数不能写路径,默认会去项目中的views目录查找该模板文件
// 也就是说Express有一个约定,开发人员会把所有的视图文件都放到views目录中
app.get('/', function (req, res) {
res.render('index.art', {
user: {
name: 'aui',
tags: ['art', 'template', 'nodejs']
}
});
});
使用
const express = require('express');
const app = express();
app.use('/public/', express.static('./public/'));
// 配置使用art-template模板引擎
// 第一个参数表示,当渲染以.art结尾的文件的时候,使用art-template模板引擎
// express-art-template是专门用来在express中把art-template整合到Express中
app.engine('html', require('express-art-template'));
// 如果想要修改默认的views目录,则可以:
// app.set('views', render函数的默认路径);
// express为response相应对象提供了一个方法:render
// render方法默认是不可以使用,但是如果配置了模板引擎就可以使用了
// res.render('html模板名', {模板数据})
// 第一个参数不能写路径,默认会去项目中的views目录查找该模板文件
// 也就是说Express有一个约定,开发人员会把所有的视图文件都放到views目录中
app.get('/', function (req, res) {
res.render('index.html');
});
app.get('/admin', function(req, res) {
res.render('admin/index.html', {
title: 'express'
});
});
app.listen(3000, function() {
console.log('port 3000');
})
案例
const express = require('express');
const app = express();
app.use('/public/', express.static('./public/'));
app.engine('html', require('express-art-template'));
const comments = [
{
name: '张三',
message: '今天天气不错!',
dateTime: '2015-10-16'
},
{
name: '张三2',
message: '今天天气不错!',
dateTime: '2015-10-16'
},
{
name: '张三3',
message: '今天天气不错!',
dateTime: '2015-10-16'
},
{
name: '张三4',
message: '今天天气不错!',
dateTime: '2015-10-16'
},
{
name: '张三5',
message: '今天天气不错!',
dateTime: '2015-10-16'
}
]
// route
app.get('/', function (req, res) {
res.render('index.html', {
comments: comments
});
});
app.get('/post', function(req, res) {
res.render('post.html');
});
app.get('/pinglun', function(req, res) {
// 获取get请求的参数
const comment = req.query;
comment.dateTime = '2021-07-28 00:00:00';
comments.unshift(comment);
res.redirect('/');
});
app.listen(3000, function() {
console.log('port 3000');
})
处理POST请求
需要使用第三方中间件 body-parser
安装
npm install --save body-parser
配置
const bodyParser = require('body-parser')
// 配置body-parser
// 只要加入了这个配置,则在req请求对象上会多出来一个属性:body
// 也就是说:你可以直接通过req.body来获取表单post请求数据了
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
使用
app.post('/post', function(req, res) {
console.log(req.body);
const comment = req.body;
comment.dateTime = '2021-07-28 00:00:00';
comments.unshift(comment);
res.redirect('/');
})
CRUD案例
app.js
const express = require('express');
const router = require('./router');
const bodyParser = require('body-parser')
const app = express();
app.engine('html', require('express-art-template'));
app.use('/public/', express.static('./public/'));
app.use('/node_modules/', express.static('./node_modules/'));
// 这里必须载挂载路由之前配置
// 配置body-parser
// 只要加入了这个配置,则在req请求对象上会多出来一个属性:body
// 也就是说:你可以直接通过req.body来获取表单post请求数据了
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
// router(app);
app.use(router);
app.listen(3000, function () {
console.log('running 3000');
})
router.js
const fs = require('fs');
const students = require('./students.js');
// 这样也不方便
// module.exports = function (app) {
// app.get('/', function (req, res) {
// fs.readFile('./db.json', 'utf8', function (err, data) {
// if (err) {
// return res.status(500).send('Server error.');
// }
// res.render('index.html', {
// students: JSON.parse(data).students
// });
// })
// })
// }
const express = require('express');
// 1. 创建一个路由容器
const router = express.Router();
// 2. 把路由都挂载到路由容器中
// 主界面
router.get('/students', function (req, res) {
students.findAll(function (err, data) {
if (err) {
return res.status(500).send('Server error');
}
res.render('index.html', {
students: data
})
})
})
// 新增页面
router.get('/students/new', function (req, res) {
res.render('new.html');
})
// 点击新增时候的处理
router.post('/students/new', function (req, res) {
const data = req.body;
students.save(data, function (err, data) {
if (err) {
return res.status(500).send('Server error');
}
res.redirect('/students');
});
})
// 编辑页面
router.get('/students/edit', function (req, res) {
const id = parseInt(req.query.id);
students.findById(id, function (err, data) {
if (err) {
return res.status(500).send('Server error');
}
res.render('edit.html', {
student: data
})
})
})
// 点击编辑时候的处理
router.post('/students/edit', function (req, res) {
const data = req.body;
students.updateById(data, function (err, data) {
if (err) {
return res.status(500).send('Server error');
}
res.redirect('/students');
})
})
// 点击删除时候的处理
router.get('/students/delete', function (req, res) {
const id = parseInt(req.query.id);
students.delete(id, function(err, data) {
if (err) {
return res.status(500).send('Server error');
}
res.redirect('/students');
});
})
module.exports = router;
students.js
// 数据操作文件模块
// 只处理数据,不关心业务
const fs = require('fs');
const dbPath = './db.json';
// 获取所有学生列表
// callback 上层定义,下层调用
exports.findAll = function (callback) {
fs.readFile(dbPath, 'utf8', function (err, data) {
if (err) {
return callback(err);
}
callback(null, JSON.parse(data).students);
})
}
// 根据ID查询学生
exports.findById = function (id, callback) {
fs.readFile(dbPath, 'utf8', function (err, data) {
if (err) {
return callback(err);
}
const students = JSON.parse(data).students;
const student = students.find(item => {
return item.id == id;
})
callback(null, student);
})
}
// 添加保存学生
exports.save = function (student, callback) {
fs.readFile(dbPath, 'utf8', function (err, data) {
if (err) {
return callback(err);
}
const students = JSON.parse(data).students;
student.id = students[students.length - 1].id + 1;
students.push(student);
const fileData = JSON.stringify({
students: students
});
fs.writeFile(dbPath, fileData, function (err) {
if (err) {
return callback(err);
}
callback(null);
});
})
}
// 更新学生
exports.updateById = function (student, callback) {
fs.readFile(dbPath, 'utf8', function (err, data) {
if (err) {
return callback(err);
}
const students = JSON.parse(data).students;
const curStudent = students.find(item => {
return item.id == student.id;
});
for (let key in student) {
curStudent[key] = student[key];
}
const fileData = JSON.stringify({
students: students
})
fs.writeFile(dbPath, fileData, function (err) {
if (err) {
return callback(err);
}
callback(null);
});
})
}
// 删除学生
exports.delete = function (id, callback) {
fs.readFile(dbPath, 'utf8', function (err, data) {
if (err) {
return callback(err);
}
const students = JSON.parse(data).students;
const studentIndex = students.findIndex(item => {
return item.id == id;
})
if (studentIndex !== -1) { students.splice(studentIndex, 1) }
const fileData = JSON.stringify({
students: students
})
fs.writeFile(dbPath, fileData, function (err) {
if (err) {
return callback(err);
}
callback(null);
});
})
}