學習網(wǎng)址
Express 框架核心特性:
- 可以設置中間件來響應 HTTP 請求褒侧。
- 定義了路由表用于執(zhí)行不同的 HTTP 請求動作良风。
- 可以通過向模板傳遞參數(shù)來動態(tài)渲染 HTML 頁面。
安裝 Express
npm install express --save
幾個重要的模塊是需要與 express 框架一起安裝的:
- body-parser 中間件闷供,用于處理 JSON, Raw, Text 和 URL 編碼的數(shù)據(jù)烟央。
- cookie-parser 這就是一個解析Cookie的工具。通過req.cookies可以取到傳過來的cookie歪脏,并把它們轉成對象疑俭。
- multer 中間件,用于處理 enctype="multipart/form-data"(設置表單的MIME編碼)的表單數(shù)據(jù)婿失。
第一個 Express 框架實例
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
})
請求和響應
- Express 應用使用回調(diào)函數(shù)的參數(shù): request 和 response 對象來處理請求和響應的數(shù)據(jù)钞艇。
request 對象表示 HTTP 請求,包含了請求查詢字符串豪硅,參數(shù)哩照,內(nèi)容,HTTP 頭部等屬性懒浮。常見屬性有:
req.app:當callback為外部文件時飘弧,用req.app訪問express的實例
req.baseUrl:獲取路由當前安裝的URL路徑
req.body / req.cookies:獲得「請求主體」/ Cookies
req.fresh / req.stale:判斷請求是否還「新鮮」
req.hostname / req.ip:獲取主機名和IP地址
req.originalUrl:獲取原始請求URL
req.params:獲取路由的parameters
req.path:獲取請求路徑
req.protocol:獲取協(xié)議類型
req.query:獲取URL的查詢參數(shù)串
req.route:獲取當前匹配的路由
req.subdomains:獲取子域名
req.accepts():檢查可接受的請求的文檔類型
req.acceptsCharsets / req.acceptsEncodings / req.acceptsLanguages:返回指定字符集的第一個可接受字符編碼
req.get():獲取指定的HTTP請求頭
req.is():判斷請求頭Content-Type的MIME類型
response 對象表示 HTTP 響應,即在接收到請求時向客戶端發(fā)送的 HTTP 響應數(shù)據(jù)。常見屬性有:
res.app:同req.app一樣
res.append():追加指定HTTP頭
res.set()在res.append()后將重置之前設置的頭
res.cookie(name次伶,value [蹋岩,option]):設置Cookie
opition: domain / expires / httpOnly / maxAge / path / secure / signed
res.clearCookie():清除Cookie
res.download():傳送指定路徑的文件
res.get():返回指定的HTTP頭
res.json():傳送JSON響應
res.jsonp():傳送JSONP響應
res.location():只設置響應的Location HTTP頭,不設置狀態(tài)碼或者close response
res.redirect():設置響應的Location HTTP頭学少,并且設置狀態(tài)碼302
res.send():傳送HTTP響應
res.sendFile(path [剪个,options] [,fn]):傳送指定路徑的文件 -會自動根據(jù)文件extension設定Content-Type
res.set():設置HTTP頭版确,傳入object可以一次設置多個頭
res.status():設置HTTP狀態(tài)碼
res.type():設置Content-Type的MIME類型
路由
- 路由決定了由誰(指定腳本)去響應客戶端請求
- 通過路由提取出請求的URL以及GET/POST參數(shù)扣囊。
// /del_user 頁面響應
app.get('/del_user', function (req, res) {
console.log("/del_user 響應 DELETE 請求");
res.send('刪除頁面');
})
// POST 請求
app.post('/', function (req, res) {
console.log("主頁 POST 請求");
res.send('Hello POST');
})
靜態(tài)文件
- Express 提供了內(nèi)置的中間件 express.static 來設置靜態(tài)文件如:圖片绰沥, CSS, JavaScript 等首尼。
- 你可以使用 express.static 中間件來設置靜態(tài)文件路徑宏蛉。例如哼丈,如果你將圖片, CSS, JavaScript 文件放在 public 目錄下
app.use(express.static('public'));
GET 方法
- 表單中通過 GET 方法提交兩個參數(shù)渠退,我們可以使用 server.js 文件內(nèi)的 process_get 路由器來處理輸入:
//index.htm 文件代碼:
<html>
<body>
<form action="http://127.0.0.1:8081/process_get" method="GET">
First Name: <input type="text" name="first_name"> <br>
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
</body>
</html>
server.js 文件代碼:
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.get('/process_get', function (req, res) {
// 輸出 JSON 格式
response = {
first_name:req.query.first_name,
last_name:req.query.last_name
};
res.end(JSON.stringify(response));
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("應用實例庇忌,訪問地址為 http://%s:%s", host, port)
})
POST 方法
- 通過 POST 方法提交兩個參數(shù)睛挚,我們可以使用 server.js 文件內(nèi)的 process_post 路由器來處理輸入
//index.html 文件代碼:
<form action="http://127.0.0.1:8081/process_post" method="POST">
First Name: <input type="text" name="first_name"> <br>
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// 創(chuàng)建 application/x-www-form-urlencoded 編碼解析
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(express.static('public'));
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.post('/process_post', urlencodedParser, function (req, res) {
// 輸出 JSON 格式
response = {
first_name:req.body.first_name,
last_name:req.body.last_name
};
res.end(JSON.stringify(response));
})
文件上傳
- 創(chuàng)建一個用于上傳文件的表單磨镶,使用 POST 方法溃蔫,表單 enctype 屬性設置為 multipart/form-data。
//index.htm 文件代碼:
<form action="/file_upload" method="post" enctype="multipart/form-data">
<input type="file" name="image" size="50" />
<input type="submit" value="上傳文件" />
</form>
//server.js 文件代碼:
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/tmp/'}).array('image'));
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.post('/file_upload', function (req, res) {
console.log(req.files[0]); // 上傳的文件信息
var des_file = __dirname + "/" + req.files[0].originalname;
fs.readFile( req.files[0].path, function (err, data) {
fs.writeFile(des_file, data, function (err) {
if( err ){
console.log( err );
}else{
response = {
message:'File uploaded successfully',
filename:req.files[0].originalname
};
}
res.end( JSON.stringify( response ) );
});
});
})
Cookie 管理
- 使用中間件向 Node.js 服務器發(fā)送 cookie 信息琳猫,以下代碼輸出了客戶端發(fā)送的 cookie 信息:
// express_cookie.js 文件
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
app.get('/', function(req, res) {
console.log("Cookies: ", req.cookies)
})
app.listen(8081)