原文地址:[Koa項(xiàng)目搭建過(guò)程]https://www.bougieblog.cn/blog/2018/04/10%20-%20Koa%E9%A1%B9%E7%9B%AE%E6%90%AD%E5%BB%BA%E8%BF%87%E7%A8%8B.html)
Java中的Spring MVC加MyBatis基本上已成為Java Web的標(biāo)配椭坚。Node JS上對(duì)應(yīng)的有Koa搜贤、Express战得、Mongoose、Sequelize等。Koa一定程度上可以說(shuō)是Express的升級(jí)版。許多Node JS項(xiàng)目已開(kāi)始使用非關(guān)系型數(shù)據(jù)庫(kù)(MongoDB)。Sequelize對(duì)非關(guān)系型數(shù)據(jù)庫(kù)(MSSQL、MYSQL晓折、SQLLite)做了支持。
Koa項(xiàng)目構(gòu)建
cnpm install -g koa-generator
// 這里一定要用koa2
koa2 /foo
Koa常用中間件介紹
koa-generator生成的應(yīng)用已經(jīng)包含常用中間件了兽泄,這里僅說(shuō)它里面沒(méi)有用到的漓概。
koa-less
app.use(require('koa-less')(__dirname + '/public'))
必須在static前use,不然會(huì)無(wú)效病梢。
stylesheets文件夾下新建styles.less胃珍,并引入所有模塊化less文件。
@import 'foo.less';
@import 'bar.less';
這樣所有的樣式會(huì)被編譯成一個(gè)style.css蜓陌。在模板(pug)中引用style.css就行了觅彰。
koa-session
// 設(shè)置app keys,session會(huì)根據(jù)這個(gè)進(jìn)行加密
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)*/
};
// 應(yīng)用中間件
app.use(session(CONFIG, app));
這個(gè)必須在router前use钮热,不然會(huì)無(wú)效填抬。
基本使用,可以當(dāng)成一個(gè)普通對(duì)象
// 賦值
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
}))
路由控制
開(kāi)發(fā)主要集中在路由控制這里隧期,包括restful接口和模板渲染
獲取參數(shù)(request)
查詢參數(shù)(?param=a)
ctx.query.param
路由參數(shù)(/:id)
ctx.params.id
POST參數(shù)(JSON或Form)
ctx.request.body
請(qǐng)求回應(yīng)(response)
服務(wù)器響應(yīng)給客戶端的數(shù)據(jù)
restful
ctx.body = yourData
模板渲染
默認(rèn)從views目錄開(kāi)始飒责,不許加文件后綴
ctx.render('layout', yourData)
路由攔截
未登錄時(shí)拒絕請(qǐng)求,這樣會(huì)返回404
const userAuth = (ctx, next) => {
let isLogin = ctx.session.isLogin
if(isLogin) return next()
}
router.use('/', userAuth)
此操作會(huì)包含在路由仆潮,如"/a"宏蛉、"/b"等,需在子路由之前use性置,不然會(huì)無(wú)效
2018-04-28 17:36更新
常用中間件
koa-static-cache
靜態(tài)緩存拾并,生產(chǎn)模式下啟用
const staticCache = require('koa-static-cache')
// 靜態(tài)緩存
app.use(staticCache(path.join(__dirname, 'public'), {
maxAge: 365 * 24 * 60 * 60
}))
koa-compress
gzip壓縮,生產(chǎn)模式下啟用
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配置
我在騰訊云申請(qǐng)的TrustAsia TLS RSA CA
一年免費(fèi)證書(shū)鹏浅。網(wǎng)上教程都是用openssl生成pem文件辟灰,其實(shí)并不需要這么做。下載后提取nginx
文件夾下的crt
和key
文件就行了篡石。
var https = require('https');
var path = require('path');
var fs = require('fs');
var options = {
key: fs.readFileSync(path.resolve(__dirname, './SSL/2_www.bougieblog.cn.key')), //ssl文件路徑
cert: fs.readFileSync(path.resolve(__dirname, './SSL/1_www.bougieblog.cn_bundle.crt')) //ssl文件路徑
};
https.createServer(options, app.callback()).listen(443);