我们使用router.get('/path',async fn)来注册一个get请求,可以在请求路径中使用带变量的/hello/:name,变量可以通过ctx.params.name访问。
//导入koa,和koa1不同,我们导入的是一个class,因此用大写的Koa表示
const
Koa =
require(
'koa');
//注意require("koa-router")返回的是函数
const
router =
require(
'koa-router')();
//创建一个KOA对象表示 web app本身
const
app =
new
Koa();
//对于任何请求app将调用该异步函数处理请求
app.
use(
async (
ctx,
next)
=>{
console.
log(
`Process
${
ctx.
request.
method
}
${
ctx.
request.
url
}
...`)
await
next();
})
//add router
router.
get(
'/hello/:name',
async(
ctx,
next)
=>{
var
name =
ctx.
params.
name;
ctx.
response.
body =
`<h1>hello,
${
name
}
</h1>`;
})
router.
get(
'/',
async(
ctx,
next)
=>{
ctx.
response.
body =
'<h1>index</h1>'
})
app.
use(
router.
routes())
app.
listen(
3000);
console.
log(
'app start at 3000...')
用router.get('/path',async fn)处理的是get请求。如果要处理post请求,可以用router.post('/path',async fn)。
用post请求处理URL 时,我们会遇到一个问题:post请求通常会发送一个表单,或者JSON,它作为request的body发送,但无论是Node提供的原生request对象,还是koa提供的request对象,都不提供解析request的body的功能。
所以我们需要引入另外一个middleware来解析原始request的请求,然后把解析后的参数绑到ctx.request.body中。
koa-bodyparser就是干这个的。