1. 程式人生 > >Koa2學習(四)POST請求

Koa2學習(四)POST請求

Koa2學習(四)POST請求

接受請求

POST請求的資料實體,會根據資料量的大小進行分包傳送。
當node.js後臺收到post請求時,會以buffer的形式將資料快取起來。Koa2中通過ctx.req.addListener('data', ...)這個方法監聽這個buffer。
我們簡單的看一下
同樣先簡單起一個服務:

const Koa = require('koa')
const app = new Koa()
app.use(async ctx => {
    const req = ctx.request
    const url = req.url // 請求的url
    const method = req.method   // 請求的方法
    ctx.req.addListener('data', (postDataChunk) => {
        console.log('收到post資料 ---->' ,postDataChunk)
    })
    ctx.body = {
        url,
        method,
    }
})
app.listen(8000)

module.exports = app

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

$ curl -d 'test' http://localhost:8000

此時看到node後臺列印:

收到post資料 ----> <Buffer 74 65 73 74>

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

解析資料

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

app.use(async ctx => {
    const req = ctx.request
    const url = req.url // 請求的url
    const method = req.method   // 請求的方法
    let post_data = ''
    ctx.req.addListener('data', (postDataChunk) => {
        console.log('收到post資料 ---->' ,postDataChunk)
        post_data += postDataChunk
    })
    ctx.req.addListener('end', () => {
        console.log('接收post資料完畢 ---->', post_data)
    })
    ctx.body = {
        url,
        method,
    }
})

再模擬一個請求:

$ curl -i -X POST -H "'Content-type':'application/json'" -d '{"ATime":"atime","BTime":"btime"}' http://localhost:8000

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

收到post資料 ----> <Buffer 7b 22 41 54 69 6d 65 22 3a 22 61 74 69 6d 65 22 2c 22
 42 54 69 6d 65 22 3a 22 62 74 69 6d 65 22 7d>
接收post資料完畢 ----> {"ATime":"atime","BTime":"btime"}

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

總結

  1. post請求會被node.js快取成多個buffer物件。
  2. 字串可以直接通過字串拼接buffer物件來獲取請求資料,但是檔案型別的資料需要特殊的處理方式。