Express 能夠說是最經典的 node.js Web 框架,其地位就比如 Tomcat、Jetty 之於 Java Web Server 的地位,本文一次總結全部 Express 的經常使用API。話很少說,讓咱們開始吧!html
啓動 --> fn1 --> fn2 --> fn3 --> ... --> 結束
node
這裏面的每一個 fn 就是中間件(middleware)express
中間件的通用寫法以下:編程
const fn = (request, response, next) => { // process current logic ... next() // pass control to the next handler } // 爲了方便起見,如下全部的fn或中間件的寫法都是這裏的fn app.use(fn) 複製代碼
express.json()
用於解析 JSON 格式的請求,用法:json
app.use(express.json()) app.use((request, response, next) => { const jsonObj = request.body // 能夠直接獲得JSON數據轉成的JS對象 }) 複製代碼
express.static()
用於在提供的目錄搭建一個靜態服務器,若是請求的文件在這個目錄中,就加載,若是不在,就跳過這行代碼。用法是:數組
app.use(express.static('static')) // 爲static目錄開啓一個靜態服務器 複製代碼
express.Router()
建立一個迷你 application,能夠像app.use()
、app.get()
、app.post()
同樣使用,具體能夠參見下方 app 的使用方法。用法:服務器
const express = require('express'); const router = express.Router(); router.get('/', function(req, res, next) { ... }); module.exports = router; 複製代碼
app.use()
最經常使用的API,掛載一箇中間件到指定位置,用法:markdown
app.use('/users', fn); 複製代碼
app.get()
第二經常使用的API,使用指定的回調函數將 HTTP GET 請求路由到指定的路徑。用法:app
app.get('/getName', fn); 複製代碼
app.post()
並列第二經常使用的API,使用指定的回調函數將 HTTP POST 請求路由到指定的路徑。用法:框架
app.post('/getName', fn); 複製代碼
req.body
用於獲取 HTTP 請求的請求體,用法:
const express = require('express') const app = express() app.use(express.json()) // 解析 application/json 格式的請求 app.use(express.urlencoded({ extended: true })) // 解析 application/x-www-form-urlencoded 格式的請求 app.post('/profile', function (req, res, next) { console.log(req.body) }) 複製代碼
req.query
獲取 HTTP 請求中的查詢參數,類型爲一個對象,其中包含路由中每一個查詢字符串參數的屬性
// GET /search?q=tobi+ferret console.dir(req.query.q) // => 'tobi ferret' // GET /shoes?order=desc&shoe[color]=blue&shoe[type]=converse console.dir(req.query.shoe.type) // => 'converse' // GET /shoes?color[]=blue&color[]=black&color[]=red console.dir(req.query.color) // => ['blue', 'black', 'red'] 複製代碼
req.path
獲取請求 URL 中的請求路徑,一般是 xxx.com 後面 / 開頭,? 以前的部分,用法:
// example.com/users?sort=desc console.dir(req.path) // => '/users' 複製代碼
res.send()
發送一個 HTTP 響應,響應體能夠是一個 Buffer 對象,一個字符串,一個對象,或者一個數組,用法:
res.send(Buffer.from('whoop')) res.send({ some: 'json' }) res.send('<p>some html</p>') res.status(404).send('Sorry, we cannot find that!') res.status(500).send({ error: 'something blew up' }) 複製代碼
res.set()
指定 HTTP 響應頭中的特定字段,用法:
res.set('Content-Type', 'text/plain') res.set({ 'Content-Type': 'text/plain', 'Content-Length': '123', ETag: '12345' }) 複製代碼
res.json()
發送一個 JSON 格式的響應,基本用法:
res.json(null) res.json({ user: 'tobi' }) res.status(500).json({ error: 'message' }) 複製代碼
先用一段示例代碼講一下參數的概念,
Route path: /users/:userId/books/:bookId Request URL: http://localhost:3000/users/34/books/8989 req.params: { "userId": "34", "bookId": "8989" } 複製代碼
router.param
構造一個參數觸發器,當參數名爲指定參數名時,觸發回調,而且只會觸發一次,用法:
router.param('id', function (req, res, next, id) { console.log('CALLED ONLY ONCE'); next(); }); router.get('/user/:id', function (req, res, next) { console.log('although this matches'); next(); }); 複製代碼
router.route()
返回單個路由實例,接下來能夠用各類中間件處理 HTTP 請求,用法:
const router = express.Router(); router.param('user_id', function(req, res, next, id) { // sample user, would actually fetch from DB, etc... req.user = { id: id, name: 'TJ' }; next(); }); router.route('/users/:user_id') .all(function(req, res, next) { // runs for all HTTP verbs first // think of it as route specific middleware! next(); }) .get(function(req, res, next) { res.json(req.user); }) .put(function(req, res, next) { // just an example of maybe updating the user req.user.name = req.params.name; // save user ... etc res.json(req.user); }) .post(function(req, res, next) { next(new Error('not implemented')); }) .delete(function(req, res, next) { next(new Error('not implemented')); }); 複製代碼