Koa项目搭建过程详细记录
Java中的Spring MVC加MyBatis基本上已成为Java Web的标配。Node JS上对应的有Koa、Express、Mongoose、Sequelize等。Koa一定程度上可以说是Express的升级版。许多Node JS项目已开始使用非关系型数据库(MongoDB)。Sequelize对非关系型数据库(MSSQL、MYSQL、SQLLite)做了支持。 Koa项目构建 cnpm install -g koa-generator // 这里一定要用koa2 koa2 /foo Koa常用中间件介绍 koa-generator生成的应用已经包含常用中间件了,这里仅说它里面没有用到的。 koa-less app.use(require('koa-less')(__dirname + '/public')) 必须在static前use,不然会无效。 stylesheets文件夹下新建styles.less,并引入所有模块化less文件。 @import 'foo.less'; @import 'bar.less'; 这样所有的样式会被编译成一个style.css。在模板(pug)中引用style.css就行了。 koa-session // 设置app keys,session会根据这个进行加密 app.keys = ['some secret hurr']; // 配置session config const CONFIG = { key: 'bougie:session', /** (string) cookie key (default is koa:sess) */ maxAge: 1000 * 60 * 60 * 24 * 7, overwrite: true, /** (boolean) can overwrite or not (default true) */ httpOnly: true, /** (boolean) httpOnly or not (default true) */ signed: true, /** (boolean) signed or not (default true) */ rolling: true, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */ renew: false, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/ }; // 应用中间件 app.use(session(CONFIG, app)); 前端全栈开发学习交流圈:866109386。面向1-3年前端人员,帮助突破技术瓶颈,提升思维能力。 这个必须在router前use,不然会无效。 基本使用,可以当成一个普通对象 // 赋值 ctx.session.statu = value // 取值 ctx.session.statu // 删除 ctx.session.statu = null koa-proxies 用于代理配置 const proxy = require('koa-proxies') app.use(proxy('/octocat', { target: 'https://api.github.com/users', changeOrigin: true, agent: new httpsProxyAgent('http://1.2.3.4:88'), rewrite: path => path.replace(/^\/octocat(\/|\/\w+)?$/, '/vagusx'), logs: true 路由控制 开发主要集中在路由控制这里,包括restful接口和模板渲染 获取参数(request) 查询参数(?param=a) ctx.query.param 路由参数(/:id) ctx.params.id POST参数(JSON或Form) ctx.request.body 请求回应(response) 服务器响应给客户端的数据 restful ctx.body = yourData 模板渲染 默认从views目录开始,不许加文件后缀 ctx.render('layout', yourData) 路由拦截 未登录时拒绝请求,这样会返回404 const userAuth = (ctx, next) => { let isLogin = ctx.session.isLogin if(isLogin) return next() } router.use('/', userAuth) 此操作会包含在路由,如"/a"、"/b"等,需在子路由之前use,不然会无效