vuvivian's blog

越努力,越幸运.

  1. 1. koa路由
  2. 2. 获取get传值
  3. 3. 获取post传值

koa路由

  • 需要安装koa-router来处理相关路由
  • 引入并实例化
  • 配置路由: router.get()
  • 启动路由:app.use()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* Created by vuvivian on 2019/12/15
*/

let Koa = require('koa'),
Router = require('koa-router');

let app = new Koa(),
router = new Router();

// 配置路由 ctx:包含request,response等上下文信息
router
.get('/',(ctx)=>{
ctx.body = '首页' // 返回数据,相当于原生的res.writeHead() res.end()
})
.get('/news',async(ctx)=>{
ctx.body = "这是一个新闻页面"
})

// 中间件

//express写法
// app.use(function(req,res){
// res.send('返回数据')
// })

// app.use( async(ctx)=>{ctx.body="hello, koa2.11"})
app.use(router.routes()) // 启动路由
app.use(router.allowedMethods()) //可选,放在router.routes()之后,此时根据cts.status配置response响应头

// 监听端口
app.listen(3000);

获取get传值

1
2


获取post传值

1
2


本文最后更新于 天前,文中所描述的信息可能已发生改变