Koa学习2
来源:互联网 发布:linux if语句 编辑:程序博客网 时间:2024/05/18 07:02
前言
学习来源:廖雪峰教程 ,
开发工具:WebStorm
该文主要记录下我自己URL的处理,参照上海电气node项目的思路来进行。
正文
思路:所有的URL处理函数都放到app.js里显得很乱,而且,每加一个URL,就需要修改app.js。随着URL越来越多,app.js就会越来越长。
如果能把URL处理函数集中到某个js文件,或者某几个js文件中就好了,然后让app.js自动导入所有处理URL的函数。
登陆业务代码:
//首页module.exports.index = async (ctx, next) => { ctx.response.body = `<h1>Index</h1> <form action="/signin" method="post"> <p>Name: <input name="name" value="koa"></p> <p>Password: <input name="password" type="password"></p> <p><input type="submit" value="Submit"></p> </form>`;}//登陆module.exports.login = async (ctx, next) => { var name = ctx.request.body.name || '', password = ctx.request.body.password || ''; console.log(`signin with name: ${name}, password: ${password}`); if (name === 'koa' && password === '12345') { ctx.response.body = `<h1>Welcome, ${name}!</h1>`; } else { ctx.response.body = `<h1>Login failed!</h1> <p><a href="/">Try again</a></p>`; }}
我们在controllers目录下编写router.js
//路由var index = require("./controllers/index");var hello = require("./controllers/hello");module.exports = function(router){ //首页 router.get('/',index.index); //登录 router.post('/signin',index.login); router.get('/hello/:name',hello.hello); //此处代码必须放在最后一行,请勿在此代码后添加任何路由 router.get('*', async (ctx, next) => { ctx.response.body = `<h1>404 Page!</h1>`; });}
优化app.js
//koaconst koa = require('koa');//参数解析const bodyParser = require('koa-bodyparser');// 注意require('koa-router')返回的是函数:const router = require('koa-router')();const app = new koa();// log request URL:app.use(async (ctx, next) => { console.log(`Process ${ctx.request.method} ${ctx.request.url}...`); await next();});//参数解析器app.use(bodyParser());//url路由require("./router")(router);// add router middleware:app.use(router.routes());app.listen(3000);console.log('app started at port 3000...');
这样,我们以后只需要再controllers里编写具体的业务代码,再router.js里注册路由URL,感觉这样比较简练清晰。
后记
下一节,练习模板引擎Nunjucks结合koa的使用,应该还是简单的登陆页面,然后成功失败页面。
阅读全文
1 0
- koa学习2——koa入门
- Koa学习2
- Koa 、Koa-router 学习整理
- koa学习一
- KOA 中文文档学习
- Koa学习笔记
- Koa学习1
- Koa
- koa学习笔记三---手写thunkify模块
- koa学习笔记----callback,promise,generator
- nodejs之koa学习笔记(1)
- KOA学习(1)——介绍,安装与运行
- nodejs学习(8)koa路由的匹配
- JavaScript之node.js-web框架Koa学习
- 使用 koa
- koa 用法
- koa源码
- koa入门教程
- 虚拟串口与虚拟机配置笔记
- LeetCode——79. Word Search
- JAVA语言:使用公式C=(5/9)*(F-32)打印下列华氏温度与摄氏温度对照表
- bat脚本
- QT 5.7.0 版本说明
- Koa学习2
- 1.8 开始第一幅“码绘”——运用条件判断,让懵逼脸能够做出不同表情
- Linux Shell脚本攻略1:小试牛刀(1)
- myeclipse打开jsp后卡死的问题详解
- ubuntu环境下搭建python3开发环境
- 京东校招前端笔试题:购物车问题
- LeetCode
- Lcs最长递增 51nod
- python hello world