iKcamp|基於Koa2搭建Node.js實戰(含視訊)☞ 解析JSON

iKcamp發表於2018-01-15

視訊地址:www.cctalk.com/v/151149238…

iKcamp|基於Koa2搭建Node.js實戰(含視訊)☞ 解析JSON

JSON 資料

我顛倒了整個世界,只為擺正你的倒影。

前面的文章中,我們已經完成了專案中常見的問題,比如 路由請求結構分層檢視渲染靜態資源等。 那麼,JSON 呢?JSON 格式資料的傳輸,已經深入到了我們的碼裡行間,脫離了 JSON 的人想必是痛苦的。那麼,複合吧!

iKcamp|基於Koa2搭建Node.js實戰(含視訊)☞ 解析JSON

如何設定 JSON 格式

偉大的武術家——李小龍先生——說過這樣一段話:

Empty your mind, Be formless,shapeless like water. 
You put water in a cup, it becomes the cup.
You put water in a bottle, it becomes the bottle. 
You put water in a teapot , it becomes the teapot. 
Water can flow or crash. 
複製程式碼

翻譯成中文意思就是:

清空你的思想,像水一樣無形。
你將水倒入水杯,水就是水杯的形狀。
你將水倒入瓶子,水就是瓶子的形狀。
你將水倒入茶壺,水就是茶壺的形狀。
你看,水會流動,也會衝擊。
複製程式碼

在資料傳輸過程中,傳輸的資源都可以稱之為『資料』,而『資料』之所以展示出不同的形態,是因為我們已經設定了它的格式。

傳輸的資料像是『水』一樣,沒有任何的格式和形狀。

我們的設定像是『器』一樣,賦予它指定的形態。

所以,我們只需要設定把資料掛載在響應體 body 上,同時告訴客戶端『返回的是 JSON 資料』,客戶端就會按照 JSON 來解析了。程式碼如下:

ctx.set("Content-Type", "application/json")
ctx.body = JSON.stringify(json)
複製程式碼

提取中介軟體

我們把上面的程式碼提取成一箇中介軟體,這樣更方便程式碼的維護性和擴充套件性

增加檔案 /middleware/mi-send/index.js

module.exports = () => {
  function render(json) {
      this.set("Content-Type", "application/json")
      this.body = JSON.stringify(json)
  }
  return async (ctx, next) => {
      ctx.send = render.bind(ctx)
      await next()
  }
}
複製程式碼

注意: 目錄不存在,需要自己建立。

程式碼中,我們把 JSON 資料的處理方法掛載在 ctx 物件中,並起名為 send。當我們需要返回 JSON 資料給客戶端時候,只需要呼叫此方法,並把 JSON 物件作為引數傳入到方法中就行了,用法如下:

ctx.send({
  status: 'success',
  data: 'hello ikcmap'
})
複製程式碼

應用中介軟體

程式碼的實現過程和呼叫方法我們已經知道了,現在我們需要把這個中介軟體應用在專案中。

  1. 增加檔案 middleware/index.js,用來集中呼叫所有的中介軟體:
const miSend = require('./mi-send')
module.exports = (app) => {
  app.use(miSend())
}
複製程式碼
  1. 修改 app.js,增加中介軟體的引用
const Koa = require('koa')
const path = require('path')
const bodyParser = require('koa-bodyparser')
const nunjucks = require('koa-nunjucks-2')
const staticFiles = require('koa-static')

const app = new Koa()
const router = require('./router')

const middleware = require('./middleware')

middleware(app)

app.use(staticFiles(path.resolve(__dirname, "./public")))

app.use(nunjucks({
  ext: 'html',
  path: path.join(__dirname, 'views'),
  nunjucksConfig: {
    trimBlocks: true
  }
}));

app.use(bodyParser())
router(app)
app.listen(3000, () => {
  console.log('server is running at http://localhost:3000')
})
複製程式碼

中介軟體遷移

隨著專案的步步完善,將會產生有更多的中介軟體。我們把 app.js 中的中介軟體程式碼遷移到 middleware/index.js 中,方便後期維護擴充套件

  1. 修改 app.js
const Koa = require('koa')
const app = new Koa()
const router = require('./router')

const middleware = require('./middleware')

middleware(app)
router(app)
app.listen(3000, () => {
  console.log('server is running at http://localhost:3000')
})
複製程式碼
  1. 修改 middleware/index.js
const path = require('path')
const bodyParser = require('koa-bodyparser')
const nunjucks = require('koa-nunjucks-2')
const staticFiles = require('koa-static')

const miSend = require('./mi-send')
module.exports = (app) => {
  app.use(staticFiles(path.resolve(__dirname, "../public")))

  app.use(nunjucks({
    ext: 'html',
    path: path.join(__dirname, '../views'),
    nunjucksConfig: {
      trimBlocks: true
    }
  }));

  app.use(bodyParser())
  app.use(miSend())
}
複製程式碼

後面我們還會開發更多的中介軟體,比如日誌記錄、錯誤處理等,都會放在 middleware/ 目錄下處理。

下一篇:記錄日誌——開發日誌中介軟體,記錄專案中的各種形式資訊

iKcamp|基於Koa2搭建Node.js實戰(含視訊)☞ 解析JSON

iKcamp|基於Koa2搭建Node.js實戰(含視訊)☞ 解析JSON

上一篇:iKcamp新課程推出啦~~~~~iKcamp|基於Koa2搭建Node.js實戰(含視訊)☞ 處理靜態資源

推薦: 翻譯專案Master的自述:

1. 乾貨|人人都是翻譯專案的Master

2. iKcamp出品微信小程式教學共5章16小節彙總(含視訊)


iKcamp|基於Koa2搭建Node.js實戰(含視訊)☞ 解析JSON

2019年,iKcamp原創新書《Koa與Node.js開發實戰》已在京東、天貓、亞馬遜、噹噹開售啦!

相關文章