Koa项目搭建过程

VukyQS.png

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))

这个必须在 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,不然会无效

2018-04-28 17:36 更新

# 常用中间件

# koa-static-cache

静态缓存,生产模式下启用

const staticCache = require('koa-static-cache')
// 静态缓存
app.use(
  staticCache(path.join(__dirname, 'public'), {
    maxAge: 365 * 24 * 60 * 60
  })
)

# koa-compress

gzip 压缩,生产模式下启用

const compress = require('koa-compress')
// gzip
app.use(
  compress({
    filter: function (content_type) {
      return /text/i.test(content_type)
    },
    threshold: 2048,
    flush: require('zlib').Z_SYNC_FLUSH
  })
)

# 404 处理

需要在 router 之后 use

// 404
app.use(async (ctx) => {
  await ctx.render('notFound')
})

# https 配置

我在腾讯云申请的TrustAsia TLS RSA CA一年免费证书。网上教程都是用 openssl 生成 pem 文件,其实并不需要这么做。下载后提取nginx文件夹下的crtkey文件就行了。

var https = require('https')
var path = require('path')
var fs = require('fs')
var options = {
  key: fs.readFileSync(
    path.resolve(__dirname, './SSL/2_bougieL.github.io.key')
  ), //ssl文件路径
  cert: fs.readFileSync(
    path.resolve(__dirname, './SSL/1_bougieL.github.io_bundle.crt')
  ) //ssl文件路径
}
https.createServer(options, app.callback()).listen(443)