express
node web應用框架,提供了很多web應用和HTTP工具
使用express可以快速搭建一個完整功能的網站
-
終端安裝
npm install express ``` /Users/lanou3g/Desktop/歸檔/server2.js 引入,創建對象
var express = require('express');
var app = express(); -
核心功能
- 路由
app.get("/", function (req, res) { res.send("哈哈哈"); }); app.listen(8888); app.get("/index.html", function (req, res) { res.sendfile(__dirname + "/index.html"); }).listen(8888);
- 請求和響應 req對象表示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.accpets():檢查請求的Accept頭的請求類型
- 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.send():傳送HTTP響應
- res.sendFile(path [,options] [,fn]):傳送指定路徑的文件 -會自動根據文件extension設定Content-Type
- res.set():設置HTTP頭,傳入object可以一次設置多個頭
- res.status():設置HTTP狀態碼
- res.type():設置Content-Type的MIME類型