上篇已經(jīng)總結(jié)了最簡單的express框架怎么用耕挨,那這篇就將實(shí)際操作結(jié)合吧。
真是每天都是被bug纏身的一天尉桩,哎筒占,什么時(shí)候能有個(gè)聰明的大腦呢,知識(shí)它就是不進(jìn)腦子啊蜘犁,著急有啥用翰苫,那說點(diǎn)有用的吧,也就這幾天才接觸的这橙,還是了解的很少啊奏窑。
此篇也只適合初學(xué)者看了导披。
express的核心
路由 、中間件良哲、模板渲染
-
首先盛卡,說下怎么用 art-template 模板吧
- 安裝
npm install art-template --save
npm install express-art-template --save
- 配置
指定解析引擎,官方給的是art
筑凫,但實(shí)際操作中,都是解析以html
為后綴的文件并村,所以我們也以html為例
app.engine('html'),require('express-art-template');
- 修改默認(rèn)的渲染路徑 (很重要)
express-art-template 默認(rèn)的渲染的目錄是views
下面的巍实,即所渲染的html模板在views目錄下,如果需要修改默認(rèn)渲染路徑如下:
app.set('views', 目錄路徑)
這個(gè)當(dāng)時(shí)不知道啥意思哩牍,踩雷比較嚴(yán)重棚潦,改了很久。
eg: 像下面這個(gè)目錄的話膝昆,就必須得改默認(rèn)渲染路徑了丸边,不然肯定得出bug啊
app.set('views','public/static');
簡單的說妹窖,如果你的html頁面在哪個(gè)目錄下,就把路徑改到哪個(gè)目錄底下
那標(biāo)準(zhǔn)的目錄長什么樣呢收叶? 這樣建目錄的話骄呼,就不需要改默認(rèn)路徑啦
下面介紹怎么用模板吧蜓萄,看怎么渲染模板。
- 使用
res.render('模板文件名'澄峰,{模板數(shù)據(jù)})
- res.render()方法也可以只加載頁面嫉沽,不用數(shù)據(jù)渲染
- 寫了res.rander() 就可以不用寫 res.send() 了,服務(wù)器會(huì)自己進(jìn)行相應(yīng)操作
app.get('/',function (req,res) {
res.render('index.html',{
data:{
"title":"你好"
}
});
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{title}}</title>
</head>
<body></body>
</html>
-
下面簡單說下 路由router.js 和 中間件 student.js吧
因?yàn)槭浅鯇W(xué)者俏竞,很頭大绸硕。剛學(xué)的話,其實(shí)只要會(huì)模板渲染就好了胞此,封裝模塊臣咖,有點(diǎn)麻煩,也有點(diǎn)繞漱牵,所以我自己也不是太會(huì)夺蛇,只是簡單的總結(jié)
(自己做的學(xué)生信息管理系統(tǒng)為例)
- router.js 文件其實(shí)是一個(gè)路由的封裝 (部分代碼)
//express有專門的包裝路由的
const express = require('express');
//導(dǎo)入文件操作模塊
const Student = require('./student');
//創(chuàng)建一個(gè)包裝路由的容器
const routor = express.Router();
//渲染首頁
routor.get("/student",function (req, res) {
});
//添加 渲染頁面 get請(qǐng)求
routor.get('/student/add',function (req,res) {
});
//修改 渲染頁面 get請(qǐng)求
routor.get('/student/edit',function (req,res) {
});
//刪除 get請(qǐng)求
routor.get('/student/delete',function (req,res) {
});
module.exports = routor; //導(dǎo)出單個(gè)
- student.js就是中間件,進(jìn)行數(shù)據(jù)操作酣胀。
router.js 調(diào)用 student.js完成請(qǐng)求的處理工作刁赦。
最讓人頭大的就是異步操作得用回調(diào)函數(shù) callback了娶聘,后面會(huì)認(rèn)真去研究一下回調(diào)函數(shù)的使用 (部分代碼)
//此例子操作的是文件 文件操作模塊
const fs = require('fs');
let dataPath = './data.json';
/**
* 獲取所有學(xué)生列表
* find的參數(shù)是 callback函數(shù)
* callback 的參數(shù)
* 第一個(gè)是err 成功是null, 錯(cuò)誤是 錯(cuò)誤對(duì)象
* 第二個(gè)是結(jié)果 成功是數(shù)組甚脉,錯(cuò)誤是undefined
* return []*/
//查詢所有信息
exports.find = function (callback) {
fs.readFile(dataPath,'utf8',function (err,data) {
if(err){
return callback(err);
}
callback(null,JSON.parse(data));
})
};
//根據(jù)id 查詢對(duì)應(yīng)的信息
exports.findByID = function(id,callback){
fs.readFile(dataPath,'utf8',function (err,data) {
if(err){
return callback(err);
}
....
callback(null,result);
})
};
- 前面的模塊都那么復(fù)雜了丸升,那app.js當(dāng)然就很簡單了,只是導(dǎo)入router.js模塊牺氨,然后把路由 掛載到 app服務(wù)中即可
const express = require("express");
const bodyParser = require('body-parser');
const router = require('./router'); //導(dǎo)入路由操作模塊
let app = express();
//公開目錄
app.use('/node_modules/',express.static('./node_modules/'));
app.use('/public',express.static('./public'));
//引入模板
app.engine('html',require('express-art-template'));
//配置 body-parser信息 得在 掛載路由之前
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//把路由 掛載到 app服務(wù)中
app.use(router);
app.listen(3030,function () {
console.log("http://localhost:3030");
});
上面的操作初學(xué)者肯定會(huì)很暈狡耻,但其實(shí)如果代碼沒那么復(fù)雜,是可以直接寫在一個(gè)件里的猴凹,不需要封裝路由夷狰,及數(shù)據(jù)操作的。
-
最后講下數(shù)據(jù)庫連接吧
我也是很淺顯的學(xué)習(xí)了一下連接數(shù)據(jù)庫郊霎,操作數(shù)據(jù)
如何配置以及增刪改查等方法沼头,在之前也總結(jié)過,這里就不說了
下面看個(gè) express + 模板渲染 + mysql 的綜合吧(部分代碼)
只看app.js文件哦 书劝,很簡單的單個(gè)文件操作进倍,沒有利用中間件及路由模塊的封裝。初學(xué)者比較適合购对。
const express = require('express');
const app = express();
//post請(qǐng)求需要導(dǎo)入第三方模塊
const bodyParser = require('body-parser');
const mysql = require('mysql');
//連接 數(shù)據(jù)庫
let connection= mysql.createConnection({
host : 'localhost',
user : 'root',
password : '***************',
database : '***'
});
connection.connect();
//指定開放目錄資源
app.use('/public/',express.static('./public'));
app.use('/views/',express.static('./views'));
//指定模板解析引擎
app.engine('html',require('express-art-template'));
//post請(qǐng)求需要的配置
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
(查詢所有的數(shù)據(jù)渲染到頁面中)
app.get('/',function (req,res) {
let sql = 'select * from test'; //查詢語句
connection.query(sql,function (err, result) {
if(err){
console.log('[SELECT ERROR] ',err.message);
return;
}
res.render('index.html',{
data: result
});
});
});
(res.render()方法可以只加載頁面猾昆,不用數(shù)據(jù)渲染)
app.get('/about',function (req,res) {
res.render('about.html');
});
(將提交的留言添加到數(shù)據(jù)庫 (數(shù)據(jù)庫中插入數(shù)據(jù)))
app.post('/message',function (req,res) {
let data = req.body;
let addSql = 'insert into comment(username,content,date,id) VALUES(?,?,?,0)';
let addSqlParams = [data.username,data.content,data.date,data.id];
connection.query(addSql,addSqlParams,function (err,result) {
if(err){
console.log('[SELECT ERROR]',err.message);
}
res.redirect('/message'); //插入數(shù)據(jù)庫之后 重定向
});
});
簡單看下評(píng)論頁面加載的模板吧,
取渲染頁面的數(shù)據(jù)data的屬性名洞斯,與所查數(shù)據(jù)庫中表的列名一致即可
<div id="content-body">
{{each data as value}}
<div class="dialog-box">
<img src="{{value.headimg}}">
<div class="triangle-div">
<span>{{value.username}}</span>
<span>{{value.date}}</span>
<div>
<span>{{value.content}}</span>
</div>
</div>
</div>
{{/each}}
</div>
很簡單的總結(jié)到此結(jié)束毡庆,以后如果深入學(xué)習(xí)的話,再深入總結(jié)吧烙如,要開始學(xué)別的了么抗。這個(gè)夏天,要加油亚铁!