原生koa路由
index.js
const Koa = require('koa');
const fs = require('fs');
const app = new Koa();
const path =require('path');
/**
*
*
* @param {*} page html文件名称
* @returns
*/
function render(page){
return new Promise((resolve,reject)=>{
let viewUrl =path.resolve(__dirname+`/${page}`);
fs.readFile(viewUrl,'binary',(err,data)=>{
if(err){
reject(err)
}else{
resolve(data)
}
})
})
}
async function route(url){
let view = 'index.html'
switch(url){
case '/':
view = 'index.html'
break
case '/index':
view = 'index.html'
break
case '/todo':
view = 'todo.html'
break
case '/404':
view = '404.html'
break
default:
break
}
let html = await render(view)
return html
}
//app.use 两种方式的中间件,使用的是async方法(ctx,next)
app.use(async(ctx)=>{
let url = ctx.request.url;
let html = await route(url);
ctx.body = html;
})
app.listen(3000);
console.log('starting at port 3000')
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>index</title>
</head>
<body>
<h1>koa2 demo index page</h1>
<p>this is a index page</p>
<ul>
<li><a href="/">"/"</a></li>
<li><a href="/index">"/index"</a></li>
<li><a href="/todo">"/todo"</a></li>
<li><a href="/404">"/404"</a></li>
<li><a href="/nofound">"/nofound"</a></li>
</ul>
</body>
</html>
koa-router中间件
const Koa = require('koa')
const fs = require('fs')
const app = new Koa()
const Router = require('koa-router')
let home = new Router()
// 子路由1
home.get('/', async ( ctx )=>{
let html = `
<ul>
<li><a href="/page/helloworld">/page/helloworld</a></li>
<li><a href="/page/404">/page/404</a></li>
</ul>
`
ctx.body = html
})
// 子路由2
let page = new Router()
page.get('/404', async ( ctx )=>{
ctx.body = '404 page!'
}).get('/helloworld', async ( ctx )=>{
ctx.body = 'helloworld page!'
})
// 装载所有子路由
let router = new Router()
router.use('/', home.routes(), home.allowedMethods())
router.use('/page', page.routes(), page.allowedMethods())
// 加载路由中间件
app.use(router.routes());
app.use(router.allowedMethods())
app.listen(3000, () => {
console.log('[demo] route-use-middleware is starting at port 3000')
})
//我们可以看到router.allowedMethods()用在了路由匹配router.routes()之后,所以在当所有路由中间件最后调用.
//只有当请求路径匹配到了/page才会执行allowedMethods
网友评论