express框架中
阿新 • • 發佈:2018-12-21
請求和響應
Express 應用使用回撥函式的引數: request 和 response 物件來處理請求和響應的資料
app.get('/', function (req, res) { // -- })
request 和 response 物件的具體介紹:
Request 物件 - request 物件表示 HTTP 請求,包含了請求查詢字串,引數,內容,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:獲取協議型別
- req.query:獲取URL的查詢引數串
- req.route:獲取當前匹配的路由
- req.subdomains:獲取子域名
- req.accepts():檢查可接受的請求的文件型別
- req.acceptsCharsets / req.acceptsEncodings / req.acceptsLanguages:返回指定字符集的第一個可接受字元編碼
- req.get():獲取指定的HTTP請求頭
- req.is():判斷請求頭Content-Type的MIME型別
Response 物件 - response 物件表示 HTTP 響應,即在接收到請求時向客戶端傳送的 HTTP 響應資料。常見屬性有:
- 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頭,不設定狀態碼或者close response
- res.redirect():設定響應的Location HTTP頭,並且設定狀態碼302
- res.render(view,[locals],callback):渲染一個view,同時向callback傳遞渲染後的字串,如果在渲染過程中有錯誤發生next(err)將會被自動呼叫。callback將會被傳入一個可能發生的錯誤以及渲染後的頁面,這樣就不會自動輸出了。
- res.send():傳送HTTP響應
- res.sendFile(path [,options] [,fn]):傳送指定路徑的檔案 -會自動根據檔案extension設定Content-Type
- res.set():設定HTTP頭,傳入object可以一次設定多個頭
- res.status():設定HTTP狀態碼
- res.type():設定Content-Type的MIME型別