nodejs之koa2 – 路由
原生路由
网站都是有多个界面的,在函数内部通过 ctx.request.url 是可以获取到当前用户请求的路径的,由此我们可以实现简单的路由,
接着上一篇的代码接着往下写。
由于每次启动都要执行 node app.js,感觉不舒服,就把启动命令配置为了 npm start,在packafe.json中的scripts中添加下面一行就好了,
"start": "node app.js",
1.首先在views目录下新建一个about.html文件,内容如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>about</title>
</head>
<body>
<h1>about</h1>
<p>This is about pages.</p>
<a href="/">这是 about.html,点击返回index.html</a>
</body>
</html>
2.将template.html重命名为 index.html 内容修改为
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hello koa2</title>
</head>
<body>
<h1>Hello Koa2!</h1>
<p>这是经过模版渲染过来的文件!</p>
<a href="/about">点击这里会进入 about.html</a>
</body>
</html>
3.然后我们根据 ctx.request.url 这个属性,进行路由的分配,app.js中的内容如下
const fs = require('fs');
const Koa = require('koa');
const app = new Koa();
app.use((ctx) => {
// ctx.body = 'hello koa2'
if(ctx.request.url == '/about'){
ctx.type = 'html';
ctx.body = fs.createReadStream('./views/about.html');
}else{
ctx.type = 'html';
ctx.body = fs.createReadStream('./views/index.html');
}
});
app.listen(1029);
console.log('koa project is starting at port 1029');
npm start 运行项目,点击a标签两个页面就回来回切换,成功。
koa-router 模块
原生的路由用起来不是很方便,我们可以使用封装好的koa-router模块,运行下面的命令安装koa-router
npm i koa-router –save
然后将app.js修改为如下
const fs = require('fs');
// 引入koa-router
const Router = require('koa-router');
const Koa = require('koa');
const app = new Koa();
const router = new Router();
// 原生实现路由
/* app.use((ctx) => {
if(ctx.request.url == '/about'){
ctx.type = 'html';
ctx.body = fs.createReadStream('./views/about.html');
}else{
ctx.type = 'html';
ctx.body = fs.createReadStream('./views/index.html');
}
}); */
// koa-router 中间件
router.get('/',async (ctx,next) => {
ctx.type = 'html';
ctx.body = fs.createReadStream('./views/index.html');
});
router.get('/about',async (ctx,next) => {
ctx.type = 'html';
ctx.body = fs.createReadStream('./views/about.html');
});
// 将 router 挂载到app上
app.use(router.routes());
app.listen(1029);
console.log('koa project is starting at port 1029');
运行项目,和原生一样的效果,代码看上去要清晰的多。
至此,简单的路由已经完成,可以愉快的写代码了,下一篇,小弟就记录一下koa的数据请求获取。
本文纯手打,有不当之处请留言!如果对小伙伴们有帮助的话,点赞啊,谢谢!