從零搭建Koa2 Server

前幾天想寫個小爬蟲程序,準備後端就用koa2。因而翻遍github與各大網站,都沒找到一個好用的、輕一點的koa2腳手架,也找不到一個清晰些的搭建介紹。github上的腳手架要麼是1.x版的koa,要麼一堆複雜的依賴。javascript

固然可能仍是有寫的比較好的吧,只是我沒找到。無論怎樣吧,我只能親自上了,就當是學習了。前端

如今把搭建過程介紹下,看能不能方便下入門的同窗。java

第一步:初始項目,引入 Koa2

官方的介紹,是很簡單的。node

$ npm install koa
const Koa = require('koa')
const app = new Koa()

// response
app.use(ctx => {
  ctx.body = 'Hello Koa'
})

app.listen(3000)

好,那咱們就先從這開始。建立一個文件夾,命名koa2。(記得先裝好node v7.6.0 以上版本)webpack

cd koa2

npm init // 一路回車,根據提示輸入信息。

npm install koa --save

而後在文件下根目錄下建立程序入口文件:index.js,並把官網介紹那段代碼貼進去。以後在命令行中執行git

node index.js

打開瀏覽器,訪問 http://localhost:3000/ ,能夠看到頁面輸出了 hello worldes6

很好,第一步已經踏出去了。相信到這裏大部分小白都沒問題,以後就開始懵逼了。就這個玩意,我該怎麼寫接口?怎麼鏈接數據庫?github

第二步:搭建路由與Controller

Koa本質上是調用一系列的中間件,來處理對應的請求,並決定是否傳遞到下一個中間件去處理。咱們來寫一個最簡單的中間件試試。web

// 剛纔index.js 中的這段代碼,咱們改寫一下。
app.use(ctx => {
  ctx.body = 'Hello Koa'
})

// 改爲以下

app.use(ctx => {
  ctx.body = `您的網址路徑爲:${ctx.request.url}`
})

這段代碼中,app.usefunction 就是最簡單的一箇中間件,接受了請求,讀出請求路徑,並返回到客戶端。從新執行下node index.js,打開瀏覽器,輸入http://localhost:3000/hhhhh,頁面輸出了您的網址路徑爲:hhhhh數據庫

因此,接口的本質,就是判斷不一樣的請求連接,幹不一樣的事情,返回相應的結果。那麼咱們得須要一個路由中間件來處理分發請求。開源的時代,固然是拿來主義了。github搜下koa-router,成功找到。根據它的介紹,咱們先在項目根目錄執行

npm install koa-router --save

而後把index.js文件再改造下。變成以下:

const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const router = new Router()

// 先註釋了,後面再解釋
// const bodyParser = require('koa-bodyparser')
// app.use(bodyParser())

router.get('/', ctx => {
  ctx.body = `這是主頁`
})

router.get('/user', ctx => {
  ctx.body = `這是user頁`
})

router.get('/post', ctx => {
  ctx.body = ctx.request.body
})

router.get('/async', async ctx => {
  const sleep = async (ms) => {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve(true)
      }, ms)
    })
  }
  await sleep(1000)
  ctx.body = `這是異步處理頁`
})

app
  .use(router.routes())
  .use(router.allowedMethods())

app.listen(3000)

從新執行 node index.js。咱們能夠看到訪問 /, /user/async,都能獲得相應的結果了。

除了那個post的方法,壓根得不到本身post的數據。

由於koa是很純粹的,你提交的數據,它並不會幫你處理。因此這裏咱們又必須引用一箇中間件來處理提交的數據--bodyparser。把上面那兩行註釋代碼解注,就能處理請求數據了。記得要先

npm install koa-bodyparser --save

另外關於async/await不明白的同窗,能夠先去看下阮老師的介紹,點擊傳送門

不過咱們不能把全部的接口都寫在這一個文件呀,因此咱們得改造下。理一下思路,路由的配置文件應該單獨一份,接口的方法應該按業務模塊分紅一個個controller。說幹就幹!

先看改造後的目錄結構,不想截圖,你們將就看看:

-koa2
  -node_modules
  -controller
    user.js
  -index.js
  -router.js
  -package.json

再來看文件變成怎麼樣了。

// index.js

const Koa = require('koa')
const app = new Koa()
const router = require('./router')
const bodyParser = require('koa-bodyparser')

app.use(bodyParser())

app
  .use(router.routes())
  .use(router.allowedMethods())

app.listen(3000)
// router.js

const Router = require('koa-router')
const router = new Router()
const user = require('./controller/user')

router.post('/user/login', user.login)
router.get('/user/profile', user.profile)

module.exports = router
// controller/user.js

const sleep = async (ms) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(true)
    }, ms)
  })
}
module.exports = {
  login (ctx) {
    ctx.body = {
      username: ctx.request.body.username
    }
  },
  async profile (ctx) {
    await sleep(1000)
    ctx.body = {
      username: '相學長',
      sex: 'man',
      age: '999'
    }
  }
}

再從新執行 node index.js。訪問相應路由,應該能獲得對應的結果了。

其餘工程化配置

好,到此爲止,咱們的server已經大體完成了,可是咱們發現一個很煩的問題就是,每次修改代碼都得從新node index.js,這也太煩了。我但願的是,每次更新代碼都能從新執行,而且幫我執行ESlint。其餘前端項目webpack那一套,不是webpack配置工程師的話,本身挪過來又改不來。

這裏我介紹個簡單的方案,nodemon + gulp。具體呢就不一步步來了,這種東西,不用太瞭解,能run起來知足本身需求就好。若是不須要eslint的話,只要安裝nodemon就好。

package.json scripts部分 修改成:

"scripts": {
  "nodemon": "nodemon index.js"
}

而後命令行執行:

npm install nodemon --save-dev

npm run nodemon

若是有eslint的需求的話,就稍微麻煩些了,eslint的init我就不貼教程了,我貼上個人gulp配置文件:

// gulpfile.js
const gulp = require('gulp')
const lint = require('gulp-eslint')
const nodemon = require('gulp-nodemon')

function lintFiles (files) {
  return gulp.src(files)
    .pipe(lint())
    .pipe(lint.format())
    // .pipe(lint.failAfterError())
}

gulp.task('eslint', () => lintFiles(['**/*.js', '!node_modules/**']))

gulp.task('eslint_nodemon', ['eslint'], () => {
  return nodemon({
    script: './app/server.js', // 項目入口文件
    tasks (changedFiles) {
      lintFiles(changedFiles)
      return []
    },
    ignore: ['build/**', 'dist/**', '.git', 'node_modules/**']
  })
})

gulp.task('default', ['eslint_nodemon'])
// package.json scripts
"scripts": {
  "start": "pm2 start index.js --watch", // 這裏用pm2 做爲線上run,有興趣的同窗能夠本身去看看
  "dev": "gulp",
  "lint": "eslint .",
  "fix": "eslint --fix ."
},

寫在最後

到這裏,我想應該能讓一部分同窗上手了。

但這只是初步的搭建了下koa。真的想投入使用,根據業務需求,可能還須要安裝數據庫驅動等中間件。對於複雜業務場景的server,還須要更加合理的設計controller,service,在這裏就很少闡述了。

若是這篇文章,可以幫助到一些同窗,下次有空再寫寫這方面相關的。

ps: 文章介紹的全部代碼都傳了一份到github,有須要的同窗請自行去看。

地址:https://github.com/wuomzfx/koa2

相關文章
相關標籤/搜索