Express provide a higher level interface of http module.
Install express:
$ npm install express --save
these important modules will be installed with express.
-
body-parser: middleware of Node.js, to handle JSON, Raw, Text and URL encoding data. -
cookie-parser: tool to parse cookie. we can get cookie by req.cookies, and parse into object -
multer: middleware of Node.js. to handle form data likeenctype="multipart/form-data"
$ npm install body-parser --save
$ npm install cookie-parser --save
$ npm install multer --save
Example
//express_demo.js
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World');
})
var server = app.listen(80, function () {
var host = server.address().address
var port = server.address().port
console.log("應(yīng)用實例,訪問地址為 http://%s:%s", host, port)
})
Request and Response
Request:
-
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:
-
res.app:同req.app一樣 -
res.append():追加指定HTTP頭 -
res.set(): 在res.append()后將重置之前設(shè)置的頭 -
res.cookie(name,value [,option]):設(shè)置Cookie -
opition: domain / expires / httpOnly / maxAge / path / secure / signed -
res.clearCookie():清除Cookie -
res.download():傳送指定路徑的文件 -
res.get():返回指定的HTTP頭 -
res.json():傳送JSON響應(yīng) -
res.jsonp():傳送JSONP響應(yīng) -
res.location():只設(shè)置響應(yīng)的Location HTTP頭,不設(shè)置狀態(tài)碼或者close response -
res.redirect():設(shè)置響應(yīng)的Location HTTP頭,并且設(shè)置狀態(tài)碼302 -
res.send():傳送HTTP響應(yīng) -
res.sendFile(path [,options] [,fn]):傳送指定路徑的文件 -會自動根據(jù)文件extension設(shè)定Content-Type -
res.set():設(shè)置HTTP頭,傳入object可以一次設(shè)置多個頭 -
res.status():設(shè)置HTTP狀態(tài)碼 -
res.type():設(shè)置Content-Type的MIME類型
Route
var express = require('express');
var app = express();
// 主頁輸出 "Hello World"
app.get('/', function (req, res) {
console.log("主頁 GET 請求");
res.send('Hello GET');
})
// POST 請求
app.post('/', function (req, res) {
console.log("主頁 POST 請求");
res.send('Hello POST');
})
// /del_user 頁面響應(yīng)
app.get('/del_user', function (req, res) {
console.log("/del_user 響應(yīng) DELETE 請求");
res.send('刪除頁面');
})
// /list_user 頁面 GET 請求
app.get('/list_user', function (req, res) {
console.log("/list_user GET 請求");
res.send('用戶列表頁面');
})
// 對頁面 abcd, abxcd, ab123cd, 等響應(yīng) GET 請求
app.get('/ab*cd', function(req, res) {
console.log("/ab*cd GET 請求");
res.send('正則匹配');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("應(yīng)用實例,訪問地址為 http://%s:%s", host, port)
})
Static Files
We can export static files using express.static
app.use(express.static('public'));
and put some pics in public dir:
node_modules
server.js
public/
public/images
public/images/logo.png
Demo:
var express = require('express');
var app = express();
app.use(express.static('public'));
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
console.log("應(yīng)用實例,訪問地址為 http://%s:%s", host, port)
})
now, we can visit pic using url: http://127.0.0.1:8081/images/logo.png
Get Method
index.html:
<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.html', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
app.get('/process_get', function (req, res) {
// 輸出 JSON 格式
response = {
first_name:req.query.first_name,
last_name:req.query.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("應(yīng)用實例,訪問地址為 http://%s:%s", host, port)
})
POST Method
index.html:
<html>
<body>
<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>
</body>
</html>
server.js
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.html', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
app.post('/process_post', urlencodedParser, function (req, res) {
// 輸出 JSON 格式
response = {
first_name:req.body.first_name,
last_name:req.body.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("應(yīng)用實例,訪問地址為 http://%s:%s", host, port)
})
File Upload
index.html
<html>
<head>
<title>文件上傳表單</title>
</head>
<body>
<h3>文件上傳:</h3>
選擇一個文件上傳: <br />
<form action="/file_upload" method="post" enctype="multipart/form-data">
<input type="file" name="image" size="50" />
<br />
<input type="submit" value="上傳文件" />
</form>
</body>
</html>
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
};
}
console.log( response );
res.end( JSON.stringify( response ) );
});
});
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("應(yīng)用實例,訪問地址為 http://%s:%s", host, port)
})
Cookie management
server.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)