Koa2學習(四)POST請求

Koa2學習(四)POST請求

接受請求

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

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字符串:java

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

此時看到node後臺打印:node

收到post數據 ----> <Buffer 74 65 73 74>

能夠看到打印的是一個buffer對象,咱們buffer對象裏的4個數字你們應該都能猜到表明了t,e,s,t四個字符串。json

解析數據

既然拿到了請求數據,那麼解析數據就好辦了。若是是普通的字符串,能夠直接經過字符串拼接來獲取。咱們更新一下核心代碼:緩存

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,
    }
})

再模擬一個請求:bash

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

能夠看到node.js後臺輸出:app

收到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 類型數據,在遇到二進制時(例如文件類型)樣的接受方式存在問題。koa

總結

  1. post請求會被node.js緩存成多個buffer對象。
  2. 字符串能夠直接經過字符串拼接buffer對象來獲取請求數據,可是文件類型的數據須要特殊的處理方式。
相關文章
相關標籤/搜索