看了廖雪峰的 node教程,koa教程没有最终完整代码,自己归纳记录下
需要用到的三个koa模块 :
npm init
npm install koa -S
npm install koa-router -S
npm install koa-bodyparser -S
目录结构:
koa/
|
+- controllers/
| |
| +- login.js <-- 处理login相关URL
| |
| +- users.js <-- 处理用户管理相关URL
|
+- app.js <-- 使用koa的js
|
+- controller.js <-- 路由js
|
+- package.json <-- 项目描述文件
|
+- node_modules/ <-- npm安装的所有依赖包
//api.js
const Koa = require('koa');
const app = new Koa();
//由于middleware的顺序很重要,这个koa-bodyparser必须在router之前被注册到app对象上
const bodyParser = require('koa-bodyparser');
app.use(bodyParser());
const controller = require('./controller');
app.use(controller());
app.listen(3000);
console.log('app started at port 3000...');
//controller.js
const fs = require('fs');
function addMapping(router, mapping) {
console.log(mapping);
for (var url in mapping) {
if (url.startsWith('GET ')) {
var path = url.substring(4);
router.get(path, mapping[url]);
console.log(`register URL mapping: GET ${path}`);
} else if (url.startsWith('POST ')) {
var path = url.substring(5);
router.post(path, mapping[url]);
console.log(`register URL mapping: POST ${path}`);
} else {
console.log(`invalid URL: ${url}`);
}
}
}
function addControllers(router) {
var files = fs.readdirSync(__dirname + '/controllers');
var js_files = files.filter((f) => {
return f.endsWith('.js');
});
for (var f of js_files) {
console.log(`process controller: ${f}...`);
let mapping = require(__dirname + '/controllers/' + f);
addMapping(router, mapping);
}
}
module.exports = function (dir) {
let
controllers_dir = dir || 'controllers', // 如果不传参数,扫描目录默认为'controllers'
router = require('koa-router')();
addControllers(router, controllers_dir);
return router.routes();
};
//login.js
var fn_index = async (ctx, next) => {
ctx.response.body = `<h1>Index</h1>
<form action="/login/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>`;
};
var fn_signin = async (ctx, next) => {console.log(ctx.request);
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="/login/index">Try again</a></p>`;
}
};
//向外暴漏的地址(和其他js文件暴漏的地址不能有重复),访问路径http://127.0.0.1:3000/login/index
module.exports = {
'GET /login/index': fn_index,
'POST /login/signin': fn_signin
};