GET
GET请求是前后端交互最常用的请求之一,常常用来进行查询操作。 那么Koa是如何接收并处理GET请求呢?
创建一个服务
const Koa = require('koa')
const app = new Koa()
app.use(async ctx => {
ctx.body = 'Hello World'
})
app.listen(8000)
复制代码
- 其中ctx是Koa2非常重要的一个上下文对象,可以把它理解为一个全局的顶层对象,Koa2里面绝大部分的属性和方法都可以通过ctx对象获取。
- 其中ctx.body就是返回的html内容。
- app.listen(...)是koa2的一个语法糖,等于运行了下面这两个方法,实质就是调用http模块创建一个监听端口的服务。
- 每收到一个http请求,koa就会调用通过app.use()注册的async函数,并传入ctx和next参数。
const http = require('http');
http.createServer(app.callback()).listen(...);
复制代码
接收请求
koa2每一个请求都会被传入到app.use()方法中,app.use会把请求信息放入到ctx中,我们可以从ctx中获取请求的基本信息。
app.use(async ctx => {
const url = ctx.url // 请求的url
const method = ctx.method // 请求的方法
const query = ctx.query // 请求参数
const querystring = ctx.querystring // url字符串格式的请求参数
ctx.body = {
url,
method,
query,
querystring,
}
})
复制代码
现在访问localhost:8000?username=zj可以看到浏览器返回
{
"url": "/?username=zj",
"method": "GET",
"query": {
"username": "zj"
},
"querystring": "username=zj"
}
复制代码
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)
复制代码
// 可以使用xmind模拟post请求或者终端模拟
$ curl -d 'test' http://localhost:8000
复制代码
此时看到node后台打印:
收到post数据 ----> <Buffer 74 65 73 74>
复制代码
解析数据
既然拿到了请求数据,那么解析数据就好办了。如果是普通的字符串,可以直接通过字符串拼接来获取。我们更新一下核心代码:
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,
}
})
复制代码
还有一种最新的写法,推荐使用(这种方法需要引入koa-bodyparser包)
app.use(async ctx => {
const formdata = ctx.request.body //所有的请求都保存在里面
todosomething //做些你想做的事情。嘿嘿
return ctx.body = {
code: '200',
msg: formadata
}
})
复制代码
我们把收到的数据,直接通过ctx.body 返回给前端。
复制代码
总结
- get的参数在ctx.request.query获取(这种方法需要引入koa-bodyparser包)
- post的参数在ctxrequest.body获取(这种方法需要引入koa-bodyparser包)
- post请求会被node.js缓存成多个buffer对象。
- 字符串可以直接通过字符串拼接buffer对象来获取请求数据,但是文件类型的数据需要特殊的处理方式。
小强前端交流群QQ群:724179055
定时分析技术和资料,欢迎大家进来一起交流。
往期回顾地址: