安装插件
- npm i koa koa-router -S
引入模块
const Koa = require('koa');
const Router = require('koa-router');
实例化
let app = new Koa();
let router = new Router();
路由配置
//localhost:9090/
router.get('/', async (ctx) => {
ctx.body = "hello 这是首页"
})
//localhost:9090/news
router.get('/news', async (ctx) => {
ctx.body = "hello 这是新闻页面"
})
//localhost:9090/articles
router.get('/articles', async (ctx) => {
ctx.body = "hello 这是文章页面"
})
- ctx表示上下文context,包含了request和response
- ctx.body相当于原生nodeJS里面的res.writeHead()+res.end()
- 路由还可以链式调用
router.get('/', async (ctx) => {
ctx.body = "hello 这是首页"
}).get('/news', async (ctx) => {
ctx.body = "hello 这是新闻页面"
}).get('/articles', async (ctx) => {
ctx.body = "hello 这是文章页面"
})
- 路由实例化的另一种方式
const Koa = require('koa');
const router = require('koa-router')();
let app = new Koa();
router.get('/', async (ctx) => {
ctx.body = "hello 这是首页"
})
router.get('/news', async (ctx) => {
ctx.body = "hello 这是新闻页面"
})
router.get('/articles', async (ctx) => {
ctx.body = "hello 这是文章页面"
})
启动路由
app
.use(router.routes())
.use(router.allowedMethods()) //请求错误时根据ctx.status自动设置response响应头,可选设置
监听端口
app.listen(9090)
GET方法传值
- 通过request接收,有两种方法,地址栏输入http://localhost:9090/news?aid=112&name=Lily
router.get('/news', async (ctx) => {
console.log(ctx.query) //返回的是格式化好的参数对象{ aid: '112', name: 'Lily' },相当于ctx.request.query
console.log(ctx.querystring) //返回的是请求字符串aid=112&name=Lily,相当于ctx.request.querystring
console.log(ctx.url) //获取url地址返回/news?aid=112&name=Lily,相当于ctx.request.url
ctx.body = "hello 这是新闻页面"
})
动态路由
- 根据地址栏传入的参数从数据库读取操作
例如输入http://localhost:9090/news/111
router.get('/news/:id', async (ctx) => { //可以有多个参数/news/id/name
console.log(ctx.params) //输入localhost:9090/news/111返回{ id: '111' },输入什么就返回什么
ctx.body = "hello 这是新闻页面"
})