AVt天堂网 手机版,亚洲va久久久噜噜噜久久4399,天天综合亚洲色在线精品,亚洲一级Av无码毛片久久精品

當前位置:首頁 > 科技  > 軟件

手把手帶你用 82 行代碼實現一個簡易版 Express 框架

來源: 責編: 時間:2024-02-06 10:09:34 334觀看
導讀本文將帶大家實現輕量級 web 框架 connect[1] 的主要功能,只要 82 行代碼就能搞定。我并沒有標題黨,因為 Express 在 v3 版本之前就是基于 connect 進行封裝的,不過在 v4 版本就將 connect 依賴移除了[2],代碼被搬到 Expr

本文將帶大家實現輕量級 web 框架 connect[1] 的主要功能,只要 82 行代碼就能搞定。lPF28資訊網——每日最新資訊28at.com

我并沒有標題黨,因為 Express 在 v3 版本之前就是基于 connect 進行封裝的,不過在 v4 版本就將 connect 依賴移除了[2],代碼被搬到 Express 倉庫里,并做了一些細微調整。因此某種程度上,學習 connect 就是在學習 Express。lPF28資訊網——每日最新資訊28at.com

connect 的 repo 描述是:“Connect is a middleware layer for Node.js”,也就是一個 Node.js 的中間件層。中間件層是一個非常有用的機制,它類似一個插件系統,讓我們可以通過插拔的方式組合不同功能來處理請求。lPF28資訊網——每日最新資訊28at.com

基本使用

先來看看 connect 的使用。lPF28資訊網——每日最新資訊28at.com

const connect = require('connect')const app = connect()// respond to all requestsapp.use(function(req, res){  res.end('Hello from Connect!/n')})// create node.js http server and listen on porthttp.createServer(app).listen(3000)

跟 Express 一樣。lPF28資訊網——每日最新資訊28at.com

另外,app 上還提供了 .listen() 方法,用于替代 http.createServer(app).listen(3000) 的冗長寫法。lPF28資訊網——每日最新資訊28at.com

app.listen(3000) // 等價于 http.createServer(app).listen(3000)

再看看中間件的使用。lPF28資訊網——每日最新資訊28at.com

app.use(function middleware1(req, res, next) {  // middleware 1  next()});app.use(function middleware2(req, res, next) {  // middleware 2  next()});

我們通過 app.use() 方法收集并使用中間件。lPF28資訊網——每日最新資訊28at.com

中間件就是一個函數,包含 3 個參數:req、res 還有 next()。在一個中間件內調用 next(),就進入到下一個中間件的執行。lPF28資訊網——每日最新資訊28at.com

同時,我們還可以為中間件指定路由,這樣中間件只在特定路徑下起作用。lPF28資訊網——每日最新資訊28at.com

app.use('/foo', function fooMiddleware(req, res, next) {  // req.url starts with "/foo"  next()})app.use('/bar', function barMiddleware(req, res, next) {  // req.url starts with "/bar"  next()})

本質上,純中間件的寫法就是在設置根路由('/'),所以會對所有請求有效。lPF28資訊網——每日最新資訊28at.com

app.use(function middleware1(req, res, next) {  // middleware 1  next()})// 等同于app.use('/', function middleware1(req, res, next) {  // middleware 1  next()})

不過還有一類特殊中間件——異常中間件,專門用于處理前面流程里的異常錯誤。lPF28資訊網——每日最新資訊28at.com

// regular middlewareapp.use(function (req, res, next) {  // i had an error  next(new Error('boom!'));});// error middleware for errors that occurred in middleware// declared before thisapp.use(function onerror(err, req, res, next) {  // an error occurred!});

異常中間件必須是 4 個參數,第一個參數就是 error,對應前面流程中傳遞給 next() 的 Error 對象。lPF28資訊網——每日最新資訊28at.com

以上,我們就講完了 connect 庫的基本使用。接下來,就著手實現。lPF28資訊網——每日最新資訊28at.com

代碼實現

基于 connect v3.7.0 版本[3]。lPF28資訊網——每日最新資訊28at.com

剛學 Node.js 的時候,我們學到第一個例子,可能就是啟動一個會說“Hello World”的服務器了。lPF28資訊網——每日最新資訊28at.com

const http = require('node:http')const hostname = '127.0.0.1'const port = 3000const server = http.createServer((req, res) => {  res.statusCode = 200  res.setHeader('Content-Type', 'text/plain')  res.end('Hello World/n')})server.listen(port, hostname, () => {  console.log(`Server running at http://${hostname}:${port}/`)})

回顧 connect 的使用。lPF28資訊網——每日最新資訊28at.com

const connect = require('connect')const app = connect()// respond to all requestsapp.use(function(req, res){  res.end('Hello from Connect!/n')})// create node.js http server and listen on portapp.listen(3000)

實現 app.listen()

我們已經知道 app.listen(3000) 內部實現就是 http.createServer(app).listen(3000)。lPF28資訊網——每日最新資訊28at.com

因此,我們先實現 .listen() 方法。lPF28資訊網——每日最新資訊28at.com

module.exports = function createApplication() {  const app = {}  app.listen = function listen(...args) {    const server = require('node:http').createServer(/* ? */)    return server.listen(...args);  }  return app}

假設 app 是一個對象。不過,http.createServer(/* ? */) 中的 ? 內容該如何實現呢?lPF28資訊網——每日最新資訊28at.com

實現 app.use()

前一步,我們做了 app.use() 的調用。lPF28資訊網——每日最新資訊28at.com

// respond to all requestsapp.use(function(req, res){  res.end('Hello from Connect!/n')})

所以,當服務啟動后,訪問 localhost:3000 時,應該返回 "Hello from Connect!" 的文本。lPF28資訊網——每日最新資訊28at.com

同時,app.use() 又支持重復調用。lPF28資訊網——每日最新資訊28at.com

// respond to all requestsapp.use(function(req, res, next) {  console.log('log req.url', req.url)  next()})// respond to all requestsapp.use(function(req, res) {  res.end('Hello from Connect!/n')})

那我們就考慮先用個數組,把通過 app.use() 調用傳入進來的回調函數存起來。lPF28資訊網——每日最新資訊28at.com

module.exports = function createApplication() {  const app = {} app.stack = []    app.use = function use(route, fn) {   let path = route   let handle = fn        // default route to '/'   if (typeof route !== 'string') {      path = '/'      handle = route    }        this.stack.push({ route: path, handle })    return this  }    app.listen = function listen(...args) {    const server = require('node:http').createServer(/* ? */)    return server.listen(...args)  }  return app}

我們把調用 app.use() 傳入的中間件都存到了 app.stack 里。lPF28資訊網——每日最新資訊28at.com

根據定義可知,http.createServer(/* ? */) 中的 ? 內容應該是一個函數。針對當前場景,它是用來處理 stack 中的這些中間件的。lPF28資訊網——每日最新資訊28at.com

實現 app.handle()

我們把這些邏輯寫在 app.handle() 內。lPF28資訊網——每日最新資訊28at.com

module.exports = function createApplication() {  const app = {}  app.stack = []  // ...  app.listen = function listen(...args) {    const server = require('node:http').createServer(app.handle.bind(app))    return server.listen(...args)  }  app.handle = function handle(res, res) {    // TODO  }  return app}

每當請求來臨,都由 app.handle 負責處理。lPF28資訊網——每日最新資訊28at.com

app.handle 的主要邏輯主要是處理 3 件事情。lPF28資訊網——每日最新資訊28at.com

  1. 獲取當前要處理的路由,沒有的話就交由最終處理函數 done
  2. 路由不匹配就跳過
  3. 路由匹配就執行當前中間件
app.handle = function handle(req, res) {  let index = 0  const done = function (err) { /* ... */ }  function next(err) {    // next callback    const layer = app.stack[index++]    // 1) all done    if (!layer) {      setImmdiate(done, err)      return    }    // route data    const path = require('node:url').parse(req.url).pathname    const route = layer.route    // 2) skip this layer if the route doesn't match    if (!path.toLowerCase().startsWith(route.toLowerCase())) {      return next(err)    }    // 3) call the layer handle    const arity = handle.length    const hasError = !!err    let error = err    try {      if (hasError && arity === 4) {        // error-handling middleware        layer.handle(err, req, res, next)        return      } else if (!hasError && arity < 4) {        // request-handling middleware        layer.handle(req, res, next)        return      }    } catch (e) {      error = e    }    next(error)  }  next()}

以上的關鍵處理就封裝在 next() 函數中。而 next() 函數就是傳遞給 connect 中間件的 next 參數。lPF28資訊網——每日最新資訊28at.com

這樣,每次請求進來,我們都會從 app.stack 的第一個中間件(stack[0])開始處理,就實現了以 next 參數為連接橋梁的中間件機制。lPF28資訊網——每日最新資訊28at.com

值得注意的是調用當前中間件的邏輯,當我們調用 layer.handle(err, req, res, next)/layer.handle(req, res, next) 時,處理流程會流入中間件內部,當內部調用 next() 函數后,控制權會重新回到 app.handle,繼續處理隊列中的下一個中間件。lPF28資訊網——每日最新資訊28at.com

當請求最終沒有任何中間件可以處理時,就會流入到 done,這是最終處理器。處理器內部,會根據是否存在錯誤,分別返回 404 或 5xx 響應。lPF28資訊網——每日最新資訊28at.com

const done = function (err) {  if (err) {    res.statusCode = err.status ?? err.statusCode ?? 500    res.statusMessage = require('node:http').STATUS_CODES[404]  } else {    res.statusCode = 404    res.statusMessage = `Cannot ${req.method} ${require('node:url').parse(req.url).pathname}`  }  res.end(`${res.statusCode} ${res.statusMessage}`)}

至此,我們基本寫完了所有的邏輯。lPF28資訊網——每日最新資訊28at.com

當然,有一個地方,可以做一個小小的優化。將 http.createServer(app.handle.bind(app)) 簡化成 http.createServer(this),不過此時 app 就不能是對象,而是函數了。lPF28資訊網——每日最新資訊28at.com

module.exports = function createApplication() { function app(req, res) { app.handle(req, res) }  // ...    app.listen = function listen(...args) {    const server = require('node:http').createServer(app)    return server.listen(...args)  }  // ...   return app}

最后,我們整體來回顧一下。lPF28資訊網——每日最新資訊28at.com

module.exports = function createApplication() {  function app(req, res) { app.handle(req, res) }  app.stack = []  app.use = function use(route, fn) {    let path = route    let handle = fn        // default route to '/'    if (typeof route !== 'string') {      path = '/'      handle = route    }    this.stack.push({ route: path, handle })    return this  }  app.listen = function listen(...args) {    const server = require('node:http').createServer(app)    return server.listen(...args)  }  app.handle = function handle(req, res) {    let index = 0    const done = function (err) {      if (err) {        res.statusCode = err.status ?? err.statusCode ?? 500        res.statusMessage = require('node:http').STATUS_CODES[404]      } else {        res.statusCode = 404        res.statusMessage = `Cannot ${req.method} ${require('node:url').parse(req.url).pathname}`      }      res.end(`${res.statusCode} ${res.statusMessage}`)    }    function next(err) {      // next callback      const layer = app.stack[index++]      // 1) all done      if (!layer) {        setImmediate(done, err)        return      }      const path = require('node:url').parse(req.url).pathname      const route = layer.route            // 2) skip this layer if the route doesn't match      if (!path.toLowerCase().startsWith(route.toLowerCase())) {        return next(err)      }      // 3) call the layer handle      const arity = handle.length      const hasError = !!err      let error = err      try {        // error-handling middleware        if (hasError && arity === 4) {          layer.handle(err, req, res, next)          return        // request-handling middleware        } else if (!hasError && arity < 4) {           layer.handle(req, res, next)          return        }      } catch (e) {        error = e      }      next(error)    }    next()  }    return app}

連上注釋,我們只用了 82 行代碼,就實現了 connect 的主要功能。lPF28資訊網——每日最新資訊28at.com

lPF28資訊網——每日最新資訊28at.com

總結

本文帶大家實現了輕量級 Web 框架 connect 的主要功能,同樣這也是一個簡易版本  Express!lPF28資訊網——每日最新資訊28at.com

實現核心是 2 個函數。lPF28資訊網——每日最新資訊28at.com

  • app.use(route, fn):用于收集中間件
  • app.handle(res, req):用于消費中間件。主要邏輯位于 next() 函數,這是傳遞給中間件的 next 參數。每一次接收請求來臨時,都由 app.handle 負責處理

而這兩個函數之間的橋梁就是 app.stack。lPF28資訊網——每日最新資訊28at.com

行文最后,給大家留一個思考題。lPF28資訊網——每日最新資訊28at.com

connect() 實例的真實實現,是支持作為子應用,掛載到父應用之上的,也就是下面的用法。lPF28資訊網——每日最新資訊28at.com

const connect = require('connect')const app = connect()const blogApp = connect()app.use('/blog', blogApp)app.listen(3000)

甚至 http.Server 實例也支持掛載。lPF28資訊網——每日最新資訊28at.com

const connect = require('connect')const app = connect()const blog = http.createServer(function(req, res){  res.end('blog')})app.use('/blog', blog)

那是如何實現呢?lPF28資訊網——每日最新資訊28at.com

大家可以參照 app.use()[4] 函數的源碼進行學習。lPF28資訊網——每日最新資訊28at.com

感謝的你的閱讀,再見~lPF28資訊網——每日最新資訊28at.com

參考資料

[1]connect: https://github.com/senchalabs/connectlPF28資訊網——每日最新資訊28at.com

[2]在 v4 版本就將 connect 依賴移除了: https://github.com/expressjs/express/compare/3.21.2...4.0.0#diff-7ae45ad102eab3b6d7e7896acd08c427a9b25b346470d7bc6507b6481575d519lPF28資訊網——每日最新資訊28at.com

[3]connect v3.7.0 版本: https://github.com/senchalabs/connect/blob/3.7.0/index.jslPF28資訊網——每日最新資訊28at.com

[4]app.use(): https://github.com/senchalabs/connect/blob/3.7.0/index.js#L76lPF28資訊網——每日最新資訊28at.com

本文鏈接:http://www.tebozhan.com/showinfo-26-74660-0.html手把手帶你用 82 行代碼實現一個簡易版 Express 框架

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 「鵝來運轉 新春添囍」!小天鵝為爾濱投送龍年新囍福利!

下一篇: 從 0 開始用 PyTorch 構建完整的 NeRF

標簽:
  • 熱門焦點
Top