一、express介紹
express 是一個基于 Node.js 平臺的極簡、靈活的 WEB 應用開發框架,簡單來說,express 是一個封裝好的工具包,封裝了很多功能,便于我們開發 WEB 應用(HTTP 服務)
二、express 使用
2.1 express 下載
express 本身是一個 npm 包,所以可以通過 npm 安裝
npm init
npm i express
2.2 express 初體驗
搭建express框架基本步驟如下:
? ? ? ?1.創建 JS 文件,鍵入如下代碼
const express = require('express')//創建express對象
const app = express();app.get('/home',(req,res)=>{res.end('hello express')
})//監聽
app.listen(9000,()=>{console.log('端口已啟動。。。')
})
? ? ? 2.命令行下執行該腳本
node <文件名>
# 或者
nodemon <文件名>
? ? ? 3.然后在瀏覽器就可以訪問 http://127.0.0.1:3000/home?
三、express 路由
3.1 什么是路由
官方定義: 路由確定了應用程序如何響應客戶端對特定端點的請求?
3.2 路由的使用?
?一個路由的組成有 請求方法 , 路徑 和 回調函數 組成
express 中提供了一系列方法,可以很方便的使用路由,使用格式如下:
app.<method>(path,callback)
示例代碼
const express = require('express')//創建express對象
const app = express();
//get路由
app.get('/home',(req,res)=>{res.end('hello express')
})
//首頁路由
app.get('/home',(req,res)=>{res.end('hello express')
})//post路由
app.post('/login',(req,res)=>{res.end('login')
})
//無論請求是什么方法,只要符合路徑就會返回結果 匹配所有方法
app.all('/test',(req,res)=>{res.end('test test')
})//匹配404
app.all('*',(req,res)=>{res.end('404 not found')
})//監聽
app.listen(9000,()=>{console.log('端口已啟動。。。')
})
3.3 獲取請求參數
express 框架封裝了一些 API 來方便獲取請求報文中的數據,并且兼容原生 HTTP 模塊的獲取方式
//導入 express
const express = require('express');
//創建應用對象
const app = express();
//獲取請求的路由規則
app.get('/request', (req, res) => {//1. 獲取報文的方式與原生 HTTP 獲取方式是兼容的console.log(req.method);console.log(req.url);console.log(req.httpVersion);console.log(req.headers);//2. express 獨有的獲取報文的方式//獲取查詢字符串console.log(req.query); // 『相對重要』// 獲取指定的請求頭console.log(req.get('host'));res.send('請求報文的獲取');
});
//啟動服務
app.listen(3000, () => {console.log('啟動成功....')
})
3.4 獲取路由參數
路由參數指的是 URL 路徑中的參數(數據)
app.get('/:id.html', (req, res) => {res.send('商品詳情, 商品 id 為' + req.params.id);
});
四、express 響應設置
express 框架封裝了一些 API 來方便給客戶端響應數據,并且兼容原生 HTTP 模塊的獲取方式
app.get("/response", (req, res) => {//1. express 中設置響應的方式兼容 HTTP 模塊的方式res.statusCode = 404;res.statusMessage = 'xxx';res.setHeader('abc', 'xyz');res.write('響應體');res.end('xxx');//2. express 的響應方法res.status(500); //設置響應狀態碼res.set('xxx', 'yyy'); //設置響應頭res.send('中文響應不亂碼'); //設置響應體//連貫操作res.status(404).set('xxx', 'yyy').send('你好朋友')//3. 其他響應res.redirect('http://atguigu.com') //重定向res.download('./package.json'); //下載響應res.json(); //響應 JSONres.sendFile(__dirname + '/home.html') //響應文件內容
});
五、express 中間件
5.1 什么是中間件
中間件(Middleware)本質是一個回調函數 中間件函數 可以像路由回調一樣訪問 請求對象(request) , 響應對象(response)
5.2 中間件的作用
中間件的作用 就是 使用函數封裝公共操作,簡化代碼
5.3 中間件的類型
- 全局中間件
- 路由中間件
5.3.1 定義全局中間件
每一個請求 到達服務端之后 都會執行全局中間件函數
聲明中間件函數
let recordMiddleware = function(request,response,next){//實現功能代碼//.....//執行next函數(當如果希望執行完中間件函數之后,仍然繼續執行路由中的回調函數,必須調用next)next();
}
應用中間件
app.use(recordMiddleware);
聲明時可以直接將匿名函數傳遞給 use
app.use(function (request, response, next) {console.log('定義第一個中間件');next();
})
5.3.2 多個全局中間件
express 允許使用 app.use() 定義多個全局中間件
app.use(function (request, response, next) {console.log('定義第一個中間件');next();
})
app.use(function (request, response, next) {console.log('定義第二個中間件');next();
})
5.3.3 定義路由中間件
如果 只需要對某一些路由進行功能封裝 ,則就需要路由中間件
調用格式如下:
app.get('/路徑',`中間件函數`,(request,response)=>{});
app.get('/路徑',`中間件函數1`,`中間件函數2`,(request,response)=>{});
?5.4 靜態資源中間件
express 內置處理靜態資源的中間件
//引入express框架
const express = require('express');
//創建服務對象
const app = express();
//靜態資源中間件的設置,將當前文件夾下的public目錄作為網站的根目錄
app.use(express.static('./public')); //當然這個目錄中都是一些靜態資源
//如果訪問的內容經常變化,還是需要設置路由
//但是,在這里有一個問題,如果public目錄下有index.html文件,單獨也有index.html的路由,
//則誰書寫在前,優先執行誰
app.get('/index.html', (request, response) => {respsonse.send('首頁');
});
//監聽端口
app.listen(3000, () => {console.log('3000 端口啟動....');
});
注意事項:
1. index.html 文件為默認打開的資源
2. 如果靜態資源與路由規則同時匹配,誰先匹配誰就響應
3. 路由響應動態資源,靜態資源中間件響應靜態資源
5.5 獲取請求體數據 body-parser
express 可以使用 body-parser 包處理請求體
第一步:安裝
npm i body-parser
第二步:導入 body-parser 包?
const bodyParser = require('body-parser');
?第三步:獲取中間件函數
//處理 querystring 格式的請求體
let urlParser = bodyParser.urlencoded({extended:false}));
//處理 JSON 格式的請求體
let jsonParser = bodyParser.json();
第四步:設置路由中間件,然后使用 request.body 來獲取請求體數據
app.post('/login', urlParser, (request,response)=>{//獲取請求體數據//console.log(request.body);//用戶名console.log(request.body.username);//密碼console.log(request.body.userpass);response.send('獲取請求體數據');
});
六、Router
6.1 什么是 Router
express 中的 Router 是一個完整的中間件和路由系統,可以看做是一個小型的 app 對象。
6.2 Router 作用
對路由進行模塊化,更好的管理路由
6.3 Router 使用
創建獨立的 JS 文件(homeRouter.js)
//1. 導入 express
const express = require('express');
//2. 創建路由器對象
const router = express.Router();
//3. 在 router 對象身上添加路由
router.get('/', (req, res) => {res.send('首頁');
})
router.get('/cart', (req, res) => {res.send('購物車');
});
//4. 暴露
module.exports = router;
主文件
const express = require('express');
const app = express();
//5.引入子路由文件
const homeRouter = require('./routes/homeRouter');
//6.設置和使用中間件
app.use(homeRouter);
app.listen(3000,()=>{console.log('3000 端口啟動....');
})
七、EJS 模板引擎
7.1 什么是模板引擎
模板引擎是分離 用戶界面和業務數據 的一種技術
7.2 什么是 EJS
EJS 是一個高效的 Ja
vascript 的模板引擎?
7.3 EJS 初體驗
下載安裝EJS
npm i ejs --save
示例代碼
//1.引入ejs
const ejs = require('ejs');
//2.定義數據
let person = ['張三','李四','王二麻子'];
//3.ejs解析模板返回結構
//<%= %> 是ejs解析內容的標記,作用是輸出當前表達式的執行結構
let html = ejs.render(‘<%= person.join(",") %>’, {person:person});
//4.輸出結果
console.log(html);
7.4 EJS 常用語法
執行JS代碼
<% code %>
輸出轉義的數據到模板上
<%= code %>
?輸出非轉義的數據到模板上
<%- code %>
?