express 快速教程


閱讀 express 官方文檔的記錄.

hello world example

var express = require('express')
var app = express()

app.get('/', function(req, res) {
    res.send('Hello World')
})

app.listen(3000, function() {
    console.log('Example app listening on port 3000!')
})

Routing

路由定義:
app.METHOD(PATH, HANDLER), METHOD 為 HTTP 請求方法, PATH 為路由路徑, HANDLER 路由回調函數, 參數為 req, res.
METHOD 還可以為 all, 它的回調函數多一個 next, 作為中間件的功能.

Route paths

路由路徑可以為字符串, 字符串模式(?, +, *, () 分別對應正則)以及正則表達式

Route parameters

路由參數是 URL 中的被捕獲的特殊位置的片段, 可以通過 req.params 對象獲取

app.get('/users/:userId/books/:bookId', function(req, res) {
    url = "http://localhost:3000/users/34/books/8989"
    req.params = {
        userId: "34",
        bookId: "8989"
    }
})

// 路徑參數名字只能為[A-Za-z0-9_]中的字符
// 因此可以使用 '-', '.' 提供一些特殊的功能
app.get('/flights/:from-:to', function(req, res) {
    url = 'http://localhost:3000/flights/SH-BJ'
    req.params = {
        from: 'SH',
        to: 'BJ'
    }
})
app.get('/plantae/:genus.:species', function(req, res) {
    url = 'http://localhost:3000/plantae/Prunus.persica'
    req.params = {
        genus: 'Prunus',
        species: 'persica'
    }
})

Route handlers

可以提供多個路由回調函數, 其中一些可以提供類似中間件的功能處理請求, 但是必須要調用 next 以調用下一個回調函數.

Response methods

express 的路由回調函數中的 res 必須調用一下方法以結束請求響應:

  • download
  • end
  • json()
  • jsonp
  • redirect
  • render
  • send
  • sendFile
  • sendStatus

app.route()

使用 app.route() 可以對一個路由鏈式調用不同的 HTTP 請求

app.route('/book')
    .get(function(req, res) {
        res.send('Get a random book')
    })
    .post(function(req, res) {
        res.send('Add a book')
    })
    .put(function(req, res) {
        res.send('Update the book')
    })

express.Router

express.Router 可以創建一個路由處理模塊

var express = require('express');
var router = express.Router();

// middleware that is specific to this router
router.use(function timeLog(req, res, next) {
  console.log('Time: ', Date.now());
  next();
});
// define the home page route
router.get('/', function(req, res) {
  res.send('Birds home page');
});
// define the about route
router.get('/about', function(req, res) {
  res.send('About birds');
});

module.exports = router;

以中間件的方式使用 express.Router

var birds = require('./birds')
app.use('/birds'', birds)

中間件

express 中的中間件就是處理 req, res, next 的函數, 中間件函數一般處理模式為:

  • 執行任意代碼
  • 對 req 和 res 進行修改
  • 結束 req - res cycle
  • next 調用下一個中間件

app 級中間件

app.use 以使用中間件

app.use(function(req, res, next) {
    // some code
    next()
})

// 對特定路由使用中間件
app.use('/user', function(req, res, next) {
    // some code
    next()
})

Router 級中間件

Router 級中間件的使用方法和 app 級的相似, 只不過中間件函數綁定在 express.Router 對象上

錯誤處理中間件

錯誤處理中間件函數與普通中間件的區別是錯誤處理多一個參數

app.use(function(err, req, res, next) {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

內置中間件

從 express 4.0 版本起, 內置中間件只有一個 express.static

Static

express 內置 express.static(root, ['options']) 中間件處理靜態文件.

app.use(express.static('public')) // Express 使用相對路徑, 因此 public 不需要在 url 中
app.use(express.static('files')) // 可以使用多個靜態中間件, 按照先后順序查找文件
app.use('/static', express.static('public')) // 添加靜態路徑到 url 中

第三方中間件

第三方中間件列表

模版

express 默認的模版引擎為 Pug

設置

app.set('views', './views') // 設置模版文件所在目錄
app.set('view engine', 'pug') // 如果需要使用其他模版

使用

// 讀取模版目錄中的 filename 文件, 用 obj 替換模版中的變量
res.render(filename, obj)

Debug

代理設備


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM