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对象来获取请求数据,但是文件类型的数据需要特殊的处理方式。
原文地址:https://www.cnblogs.com/shenshangzz/p/9973387.html