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 類型數據,在遇到二進制時(例如文件類型)樣的接受方式存在問題。
總結
- post請求會被node.js緩存成多個buffer對象。
- 字符串可以直接通過字符串拼接buffer對象來獲取請求數據,但是文件類型的數據需要特殊的處理方式。
