一、express
express
中介軟體,如下所示:
app.use
用來註冊中介軟體,先收集起來- 遇到
http
請求,根據 path
和 method
判斷觸發哪些 - 實現
next
機制,即上一個通過 next
觸發下一個
express
中介軟體的實現內部原理,程式碼如下所示:
const http = require('http')
const slice = Array.prototype.slice
class LikeExpress {
constructor () {
this.routes = {
all: [],
get: [],
post: []
}
}
register (path) {
const info = {}
if (typeof path === 'string') {
info.path = path
info.stack = slice.call(arguments, 1)
} else {
info.path = '/'
info.stack = slice.call(arguments, 0)
}
return info
}
use () {
const info = this.register.apply(this, arguments)
this.routes.all.push(info)
}
get () {
const info = this.register.apply(this, arguments)
this.routes.all.push(info)
}
post () {
const info = this.register.apply(this, arguments)
this.routes.all.push(info)
}
match (method, url) {
let stack = []
if (url === '/favicon.ico') {
return stack
}
let cutRoutes = []
cutRoutes = cutRoutes.concat(this.routes.all)
cutRoutes = cutRoutes.concat(this.routes[method])
cutRoutes.forEach(routeInfo => {
if (url.indexOf(routeInfo.path) === 0) {
stack = stack.concat(routeInfo.stack)
}
})
return stack
}
handle(req, res, stack) {
const next = () => {
const middleware = stack.shift()
if (middleware) {
middleware(req, res, next)
}
}
next()
}
callback () {
return (req, res) => {
res.json = (data) => {
res.setHeader('Content-type', 'application/json')
res.end(JSON.stringify(data))
}
const url = req.url
const method = req.method.toLowerCase()
const resultList = this.match(method, url)
this.handle(req, res, resultList)
}
}
listen (...args) {
const server = http.createServer(this.callback())
server.listen(...args)
}
}
module.exports = () => {
return new LikeExpress()
}
express
中介軟體原理的應用,程式碼如下所示:
const express = require('./like-express')
const app = express()
app.use((req, res, next) => {
console.log('請求開始...', req.method, req.url)
next()
})
app.use((req, res, next) => {
console.log('處理 cookie...')
req.cookie = {
userId: 'abc123'
}
next()
})
app.use('/api', (req, res, next) => {
console.log('處理 /api 路由')
next()
})
app.get('/api', (req, res, next) => {
console.log('處理 /api 路由')
next()
})
app.post('/api', (req, res, next) => {
console.log('處理 /api 路由')
next()
})
function loginCheck(req, res, next) {
setTimeout(() => {
console.log('模擬登入成功')
next()
})
}
app.get('/api/get-cookie', loginCheck, (req, res, next) => {
console.log('get /api/get-cookie')
res.json({
errno: 0,
data: req.cookie
})
})
app.use((req, res, next) => {
console.log('處理 404')
res.json({
errno: -1,
msg: '404 not found'
})
})
app.listen(8000, () => {
console.log('server is running on port 8000')
})