Koa项目搭建过程详细记录

Java中的Spring MVC加MyBatis基本上已成为Java Web的标配。Node JS上对应的有Koa、Express、Mongoose、Sequelize等。Koa必定程度上能够说是Express的升级版。许多Node JS项目已开始使用非关系型数据库(MongoDB)。Sequelize对非关系型数据库(MSSQL、MYSQL、SQLLite)作了支持。css

Koa项目构建前端

cnpm install -g koa-generator
 
// 这里必定要用koa2
koa2 /foo

Koa经常使用中间件介绍git

koa-generator生成的应用已经包含经常使用中间件了,这里仅说它里面没有用到的。github

koa-less数据库

app.use(require('koa-less')(__dirname + '/public'))

必须在static前use,否则会无效。 stylesheets文件夹下新建styles.less,并引入全部模块化less文件。npm

@import 'foo.less';
@import 'bar.less';

这样全部的样式会被编译成一个style.css。在模板(pug)中引用style.css就好了。api

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年前端人员,帮助突破技术瓶颈,提高思惟能力。restful

这个必须在router前use,否则会无效。 基本使用,能够当成一个普通对象cookie

// 赋值
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,否则会无效

相关文章
相关标签/搜索