1.dependencies
"co-mysql": "^1.0.0",
"koa": "^2.7.0",
"koa-better-body": "^3.0.4",
"koa-ejs": "^4.2.0",
"koa-router": "^7.4.0",
"koa-session": "^5.12.0",
"koa-static": "^5.0.0",
"mysql": "^2.17.1"
2. 主服务
引包
1 const fs = require('fs');2 const path = require('path');3 const Koa = require('koa');4 const Router = require('koa-router');5 const session = require('koa-session');6 const ejs = require('koa-ejs');7 const body = require('koa-better-body');8
9 const _static = require('./routers/static');10 const config = require('./config');11
12 const app = newKoa();13 const router = new Router();
错误处理
1 router.all('*', async (ctx, next) =>{ // * 表示所有的请求,都会经过这里的处理2 try{3 await next();4 } catch(e) {5 ctx.throw(500, e);6 }7 });
服务端渲染 koa-ejs
1 ejs(app, {2 root: path.resolve(__dirname, 'template'), // 模版路劲3 layout: false, // 使用 render 方法渲染模版时有所区别,如果省略,会去找 template/layout.ejs
// false: ctx.render('admin/index.ejs') 'abc': ctx.render('abc/admin/index.ejs')4 viewExt: 'ejs',// 模版后缀名5 cache: false, // 缓存6 debug: false // 如果是 true,会把编译之后的内容全部输出
7 });
路由 koa-router
1 router.use('/admin', require('./routers/admin')); //localhost:8080/admin/xxx
2 router.use('/api', require('./routers/api')); //localhost:8080/api/xxx
3 router.use('', require('./routers/www')); //'' 表示根,localhost:8080/xxx
开放静态资源 koa-static
_static(router, {
imageMaxAge: config.imageMaxAge,
scriptMaxAge: config.scriptMaxAge,
styleMaxAge: config.styleMaxAge,
htmlMaxAge: config.htmlMaxAge,
otherMaxAge: config.otherMaxAge
});
/*
// 上面只是封装了, 比如
// ...
const static = require('koa-static');
// ...
router.all(/.jsx?/i, static(path, options));
*/
session koa-session
1. .keys 文件是通过脚本生成的用来 session 签名的密钥,数组,每个元素都是无规律的不同字符组合
2. 这里可以使用同步读取文件的方式,因为是在启动服务的时候,只读取一次,所以,不会影响服务器性能
1 app.keys = fs.readFileSync('.keys').toString().split('rn');2 app.use(session({3 maxAge: 20 * 60 * 1000, //缓存时间 20 分钟
4 renew: true //自动续期
5 }, app));
处理 POST 数据 koa-better-body
1 app.use(body({2 uploadDir: config.UPLOAD_DIR3 }));
数据库 mysql co-mysql
1 app.context.db = require('./libs/database'); // app.context 相当于 ctx 的原型,所以,可以使用 ctx.db,query(sql语句) 来操作数据库
配置
1. 很多地方都需要 config,直接加到 app.context 上,通过 ctx.config 使用
1 app.context.config = config;
1 app.listen(config.HTTP_PORT, () =>console.log(`Server running on ${config.HTTP_PORT}...`));2 app.use(router.routes());
3. 数据库
1 const mysql = require('mysql');2 const co = require('co-mysql');3
4 const config = require('../config');5
6 const conn =mysql.createPool({7 host: config.DB_HOST,8 user: config.DB_USER,9 password: config.DB_PASS,10 port: config.DB_PORT,11 database: config.DB_NAME12 });13
14 module.exports = co(conn);
4. md5
1 const crypto = require('crypto');2 const config = require('../config');3
4 module.exports ={5 //生成 md5 值
6 md5 (buffer) {7 const obj = crypto.createHash('md5');8 obj.update(buffer +config.MD5_KEYS);9 return obj.digest('hex');10 }11 };