1. 程式人生 > >express框架中

express框架中

請求和響應

Express 應用使用回撥函式的引數: requestresponse 物件來處理請求和響應的資料

app.get('/', function (req, res) {
   // --
})

 requestresponse 物件的具體介紹:

Request 物件 - request 物件表示 HTTP 請求,包含了請求查詢字串,引數,內容,HTTP 頭部等屬性。常見屬性有:

  1. req.app:當callback為外部檔案時,用req.app訪問express的例項
  2. req.baseUrl:獲取路由當前安裝的URL路徑
  3. req.body / req.cookies:獲得「請求主體」/ Cookies
  4. req.fresh / req.stale:判斷請求是否還「新鮮」
  5. req.hostname / req.ip:獲取主機名和IP地址
  6. req.originalUrl:獲取原始請求URL
  7. req.params:獲取路由的parameters
  8. req.path:獲取請求路徑
  9. req.protocol:獲取協議型別
  10. req.query:獲取URL的查詢引數串
  11. req.route:獲取當前匹配的路由
  12. req.subdomains:獲取子域名
  13. req.accepts():檢查可接受的請求的文件型別
  14. req.acceptsCharsets / req.acceptsEncodings / req.acceptsLanguages:返回指定字符集的第一個可接受字元編碼
  15. req.get():獲取指定的HTTP請求頭
  16. req.is():判斷請求頭Content-Type的MIME型別

Response 物件 - response 物件表示 HTTP 響應,即在接收到請求時向客戶端傳送的 HTTP 響應資料。常見屬性有:

  1. res.app:同req.app一樣
  2. res.append():追加指定HTTP頭
  3. res.set()在res.append()後將重置之前設定的頭
  4. res.cookie(name,value [,option]):設定Cookie
  5. opition: domain / expires / httpOnly / maxAge / path / secure / signed
  6. res.clearCookie():清除Cookie
  7. res.download():傳送指定路徑的檔案
  8. res.get():返回指定的HTTP頭
  9. res.json():傳送JSON響應
  10. res.jsonp():傳送JSONP響應
  11. res.location():只設置響應的Location HTTP頭,不設定狀態碼或者close response
  12. res.redirect():設定響應的Location HTTP頭,並且設定狀態碼302
  13. res.render(view,[locals],callback):渲染一個view,同時向callback傳遞渲染後的字串,如果在渲染過程中有錯誤發生next(err)將會被自動呼叫。callback將會被傳入一個可能發生的錯誤以及渲染後的頁面,這樣就不會自動輸出了。
  14. res.send():傳送HTTP響應
  15. res.sendFile(path [,options] [,fn]):傳送指定路徑的檔案 -會自動根據檔案extension設定Content-Type
  16. res.set():設定HTTP頭,傳入object可以一次設定多個頭
  17. res.status():設定HTTP狀態碼
  18. res.type():設定Content-Type的MIME型別