GET请求是先后端交互最经常使用的请求之一,经常用来进行查询操做。 那么Koa是如何接收并处理GET请求呢?html
建立一个服务前端
const Koa = require('koa')
const app = new Koa()
app.use(async ctx => {
ctx.body = 'Hello World'
})
app.listen(8000)
复制代码
const http = require('http');
http.createServer(app.callback()).listen(...);
复制代码
koa2每个请求都会被传入到app.use()方法中,app.use会把请求信息放入到ctx中,咱们能够从ctx中获取请求的基本信息。node
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请求的数据实体,会根据数据量的大小进行分包传送。 当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>
复制代码
既然拿到了请求数据,那么解析数据就好办了。若是是普通的字符串,能够直接经过字符串拼接来获取。咱们更新一下核心代码:bash
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包)session
app.use(async ctx => {
const formdata = ctx.request.body //全部的请求都保存在里面
todosomething //作些你想作的事情。嘿嘿
return ctx.body = {
code: '200',
msg: formadata
}
})
复制代码
咱们把收到的数据,直接经过ctx.body 返回给前端。
复制代码
小强前端交流群QQ群:724179055app
定时分析技术和资料,欢迎你们进来一块儿交流。koa
往期回顾地址: