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