建立一個Express
應用.express()
是一個由express
模塊導出的入口top-level
函數.
const express = require('express'); let app = express();
express.static(root, [options])
express.static
,是Express
內置的惟一一箇中間件.是基於serve-static
開發的,負責託管Express
應用內的靜態資源.root
,參數指的是靜態資源文件所在的根目錄.options
,對象是可選的,支持如下屬性javascript
dotfiles
,String
類型,服務dotfiles
的選項.可能的值是allow
,deny
,ignore
,默認值爲ignore
maxAge
,以毫秒爲單位設置Cache-Control
標題頭的最大屬性或ms
格式的字符串,默認爲0
etag
,Boolean
類型,啓用或禁用etag
生成extensions
,Mixed
,設置文件擴展index
,Boolean
類型,發送目錄索引,設置false
爲禁用redirect
,Boolean
類型,當路徑是一個目錄時,重定向到尾隨/
,etHeaders
,Function
類型,設置HTTP
標頭以供文件使用的函數Etag
ETag
是HTTP1.1
中才加入的一個屬性,用來幫助服務器控制Web
端的緩存驗證.它的原理是這樣的,當瀏覽器請求服務器的某項資源A
時, 服務器根據A
算出一個哈希值(3f80f-1b6-3e1cb03b)
並經過ETag
返回給瀏覽器,瀏覽器把3f80f-1b6-3e1cb03b
和A
同時緩存在本地,當下次再次向服務器請求A時,會經過相似If-None-Match: "3f80f-1b6-3e1cb03b"
的請求頭把ETag
發送給服務器,服務器再次計算A
的哈希值並和瀏覽器返回的值作比較,若是發現A
發生了變化就把A返回給瀏覽器200
,若是發現A
沒有變化就給瀏覽器返回一個304
未修改.這樣經過控制瀏覽器端的緩存,能夠節省服務器的帶寬,由於服務器不須要每次都把全量數據返回給客戶端.注:
HTTP
中並無指定如何生成ETag
,哈希是比較理想的選擇.html
const express = require('express'); let app = express(); app.get('/', (req, res) => { res.send('hello world'); }); app.listen(3000);
app
對象的locals
屬性locals
對象上自定義屬性app.locals.title = 'my express title';
app.locals.email = 'express@express.com';
{ settings: { 'x-powered-by': true, etag: 'weak', 'etag fn': [Function: wetag], env: 'development', 'query parser': 'extended', 'query parser fn': [Function: parseExtendedQueryString], 'subdomain offset': 2, 'trust proxy': false, 'trust proxy fn': [Function: trustNone], view: [Function: View], views: 'E:\\Self\\point\\views', 'jsonp callback name': 'callback' }, title: 'my express title', email: 'express@express.com' }
app.all(path, callback(req, res, next){...})
app.all('*', fn1, fn2...) // 等價於 app.all('*', fn1) app.all('*', fn2)
app.delete(path, callback [, callback ...])
app.delete('/', function (req, res) { res.send('DELETE request to homepage'); });
app.disable(name)
,app.disabled(name)
app.able(name)
,app.abled(name)
app.set('username', 'express server'); console.log(app.get('username')); //express server app.set('username', 'express server'); app.disable('username'); console.log(app.get('username')); //false
app.engine(ext, callback)
app.engine('jade', require('jade').__express); app.engine('html', require('ejs').renderFile);
app.set('title', 'text'); console.log(app.get('title')); // text
get
請求app.get(path, callback [, callback ...])
HTTP
獲取請求路由到具備指定回調函數的指定路徑app.get('/', function (req, res) { res.send('GET request to homepage'); });
app.listen(port, [hostname], [backlog], [callback(err)])
const express = require('express'); let app = express(); app.get('/', function (req, res) { res.send('home page'); }); app.listen(3000, 'localhost', 100, function (err) { if (err) { console.log('error'); } else { console.log('the http server is running at localhost:3333'); } });
app.param([name],callback(req, res, next, id){...})
將回調觸發器添加到路由參數, 其中名稱是參數的名稱或它們的數組, 函數是回調函數.回調函數的參數是請求對象、響應對象、下一個中間件以及該參數的值 (按該順序).若是 name 是一個數組, 則回調觸發器按聲明的順序註冊在其中聲明的每一個參數.此外, 對於每一個已聲明的參數, 除了最後一個外, 回調中的下一個調用將調用下一個聲明的參數的回調.對於最後一個參數, 調用 next 將調用當前正在處理的路由的下一個中間件, 就像若是名稱只是一個字符串同樣.java
app.param('id', (req, res, next, id) => { console.log('called only once'); next(); }); app.get('/user/:id', (req, res, next) => { console.log('although this matches'); next(); }); app.get('/user/:id', (req, res) => { console.log('this matches too'); res.send('end user id'); }); /** called only once although this matches this matches too */
app.param(['id', 'page'], (req, res, next, id) => { console.log('called only once', id); next(); }); app.get('/user/:id/:page', (req, res, next) => { console.log('although this matches'); next(); }); app.get('/user/:id/:page', (req, res) => { console.log('this matches too'); res.send('end user id'); }); /** called only once kkk called only once 555 although this matches this matches too */
app.path()
let express = require('express'); let app = express(); let blog = express(); let blogAdmin = express(); app.use('/blog', blog); blog.use('/admin', blogAdmin); console.log(app.path()); console.log(blog.path()); console.log(blogAdmin.path());
app.render(view, [locals], callback(err,html){...})
app.route(path)
app.route('/one') .all(function (req, res, next) { console.log('route all'); next(); }) .get(function (req, res, next) { res.json({ code: 2589, msg: 'route get msg' }); }) .post(function (req, res, next) { res.send('this is route post send msg'); });
app.use([path,] callback(req, res, next){...})
/
app.use()
中間件可使用正則匹配路徑,能夠有多箇中間件函數app.use(express.static(__dirname + '/public')); app.use('/static', express.static(__dirname + '/public')); app.use(express.static(__dirname + '/public')); app.use(logger()); app.use(express.static(__dirname + '/public')); app.use(express.static(__dirname + '/files')); app.use(express.static(__dirname + '/uploads'));
app.use('/user/person', (req, res, next) => { console.log(req.originalUrl); // /user/person console.log(req.baseUrl); // /user/person console.log(req.path); // / next(); });
app.use(callback())
,就不會觸發app.get('/', callback())
// this middleware will not allow the request to go beyond it app.use((req, res, next) => { res.send('Hello World'); }) // requests will never reach this route app.get('/', (req, res) => { res.send('Welcome'); })