Skip to content

Instantly share code, notes, and snippets.

@robertu7
Last active August 29, 2015 14:16
Show Gist options
  • Save robertu7/1dad589806a8d38aaa65 to your computer and use it in GitHub Desktop.
Save robertu7/1dad589806a8d38aaa65 to your computer and use it in GitHub Desktop.
Express API 筆記
Application
- app.locals:定義本地變量
- app.mountpath:獲取 mounted 的 sub app 的路徑
- app.all():匹配所有 HTTP verbs
- app.engine():註冊渲染引擎
- app.listen():監聽端口
- app.param():給指定 paramter 添加 callback
- app.set() / app.get( ):設置 / 獲取常量
- app.user():安裝中間件
* 設置靜態文件訪問:app.use(express.static(__dirname + '/public'))
Request
- req.app:當 callback 為外部文件時,用 req.app 訪問 express 的實例
* 外部的 req.app == 內部的 app
- req.baseUrl:獲取路由當前安裝的 URL 路徑
- req.body / req.cookies:獲得「請求主體」/ Cookies
* 需使用 body-parser 等中間件
- req.fresh / req.stale:判斷請求是否還「新鮮」
- req.hostname / req.ip:獲取主機名和 IP 地址
- req.originalUrl:獲取原始請求 URL
- req.params:獲取路由的 parameters
- req.path:獲取請求路徑
- req.protocol:獲取協議類型
- req.query:獲取 URL 的查詢參數串
- req.route:獲取當前匹配的路由
- req.subdomains:獲取子域名
- req.accpets():檢查請求的 Accept 頭的請求類型
- 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() 後將重置之前設置的頭
- 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 響應
* 默認處理 ?callback=fucn
* 可以 app.set('jsonp callback name', 'cb') 設定為 ?cb=func
- res.location():只設置響應的 Location HTTP 頭,不設置狀態碼或者 close response
- res.redirect():設置響應的 Location HTTP 頭,並且設置狀態碼 302
- res.send():傳送 HTTP 響應
- res.sendFile(path [, options] [, fn]):傳送指定路徑的文件
- 會自動根據文件 extension 設定 Content-Type
* opitions:maxAge / root / lastModified / headers / dotfiles
* 為什麼不用 app.use('/static', express.static(__dirname)); 代替?
- res.set():設置 HTTP 頭,傳入 object 可以一次設置多個頭
- res.status():設置 HTTP 狀態碼
- res.type():設置 Content-Type 的 MIME 類型
Middleware
- Application Level Middleware: app.use() / app.VERB()
* 若沒填 path,處理全部請求
* 若 path 為 ‘/',app.use() 會處理所有 ‘/' 下的請求,而 app.VERB() 只處理 ‘/‘ 這個請求
* 若要跳過當前 middleware stack,處理下一個 middleware stack,用 next(‘route’),注意不能用於 app.use()
- Router level middleware:router.use() / router.VERB()
- Built-in middleware:express.static()
- 錯誤處理(error handler)
* app.use(function(req, res, next){next(‘err message')}
* app.use(function(err, req, res, next){console.log(err)}) //‘err message'
注意:詳細信息查看官網 API Docs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment