首頁  >  文章  >  web前端  >  具體分析Koa項目搭建

具體分析Koa項目搭建

php中世界最好的语言
php中世界最好的语言原創
2018-06-08 14:12:531483瀏覽

這次帶給大家具體分析Koa專案搭建,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));

這個必須在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,不然會無效######相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章! ######推薦閱讀:#########vue中有哪些循環遍歷指令################實作彈窗功能的兩個方法## #######

以上是具體分析Koa項目搭建的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn