Koa2學習(四)POST請求

2022-07-12 10:48:15 字數 1329 閱讀 7805

post請求的資料實體,會根據資料量的大小進行分包傳送。

當node.js後台收到post請求時,會以buffer的形式將資料快取起來。koa2中通過ctx.req.addlistener('data', ...)這個方法監聽這個buffer。

我們簡單的看一下

同樣先簡單起乙個服務:

const koa = require('koa')

const req = ctx.request

const url = req.url // 請求的url

const method = req.method // 請求的方法

ctx.req.addlistener('data', (postdatachunk) => )

ctx.body =

})

在終端模擬乙個http post請求,傳入簡單的test字串:

$ curl -d 'test' http://localhost:8000
此時看到node後台列印:

收到post資料 ---->
可以看到列印的是乙個buffer物件,我們buffer物件裡的4個數字大家應該都能猜到代表了t,e,s,t四個字串。

既然拿到了請求資料,那麼解析資料就好辦了。如果是普通的字串,可以直接通過字串拼接來獲取。我們更新一下核心**:

const req = ctx.request

const url = req.url // 請求的url

const method = req.method // 請求的方法

let post_data = ''

ctx.req.addlistener('data', (postdatachunk) => )

ctx.req.addlistener('end', () => )

ctx.body =

})再模擬乙個請求:

可以看到node.js後台輸出:

收到post資料 ----> 接收post資料完畢 ---->
注意,對於字串類post資料,上面以字串接收是沒問題的,但其實 postdatachunk 是乙個 buffer 型別資料,在遇到二進位制時(例如檔案型別)樣的接受方式存在問題。

post請求會被node.js快取成多個buffer物件。

字串可以直接通過字串拼接buffer物件來獲取請求資料,但是檔案型別的資料需要特殊的處理方式。

Koa2基礎學習

01 環境準備 安裝搭建專案的開發環境 02 中介軟體用法 講解 koa2 中介軟體的用法及如何開發中介軟體 03 路由koa router 04 post get請求 常見請求方式處理 05 分層 梳理 漸近於 mvc 分層模式 06 檢視nunjucks koa 預設支援的模板引擎 07 處理靜...

koa2入門學習

koa模組 koa route 路由 route.get 路徑 路由函式 koa static 靜態資源載入 const serve 路徑 koa compose 中介軟體合成模組 koa body 提取表單post請求鍵值對,處理上傳檔案 上下文context的response和request c...

Koa2原始碼學習

koa 基於 node.js 平台的下一代 web 開發框架 const koa require koa do some thing 以上 構建了乙個簡單的伺服器,你可以在瀏覽器輸入 localhost 8080 來訪問 下面我們通過建立koa伺服器,且傳送一次http請求來了解原始碼 在koa例項...