koa相關

koa基礎使用

  1. 創建空文件夾koas
  2. 終端中進入該目錄執行npm init -y
  3. 安裝koa:npm install --save koa
  4. 創建index.js入口文件
const Koa = require('koa')
const app = new Koa()

app.use(async ctx => {
  ctx.body = 'hello'
})
app.listen(3000)
  1. 執行node index.js
  2. 在瀏覽器中輸入:localhost:3000

koa-router使用

  1. 安裝依賴:npm install -S koa-router
  2. 重新編輯index.js
const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const router = new Router()

router.get('/', ctx=>{
  console.log(ctx)
  console.log(ctx.request)
  ctx.body = 'hello'
})
router.get('/api', ctx=>{
  console.log(ctx)
  console.log(ctx.request)
  ctx.body = 'hello api'
})

app.use(router.routes()).use(router.allowedMethods())
app.listen(3000)
  1. 執行node index.js
  2. 在瀏覽器中輸入:localhost:3000 頁面顯示hello
  3. 在瀏覽器中輸入:localhost:3000/api 頁面顯示hello api

koa開發RESTful接口

使用到的中間件

  1. 路由:koa-router
  2. 協議解析:koa-body
  3. 跨域處理:@koa/cors
使用上面的中間件
  1. 安裝依賴中間件:npm install koa-router koa-body @koa/cors -S
  2. 編輯index.js
const Koa = require('koa')
const Router = require('koa-router')
const cors = require('@koa/cors')
const koaBody = require('koa-body')

const app = new Koa()
const router = new Router()

router.post('/post', async (ctx) => {
  let {body} = ctx.request
  console.log(body)
  console.log(ctx.request)
  ctx.body = {
    ...body
  }
})

app.use(koaBody())
app.use(cors())
app.use(router.routes()).use(router.allowedMethods())
app.listen(3000)
  1. 執行node index.js
  2. 在postman中測試localhost:3000/post 接口

路由路徑前綴設置

// 這樣所有的接口都必須以api開頭才能用
router.prefix('/api')

獲取get請求中的參數

ctx.request.query

使用koa-json優化返回的數據的格式

  1. 安裝依賴:npm install -S koa-json
  2. 使用
const json = require('koa-json')
app.use(json())

koa路由進階配置

開發目錄結構

  1. 按照功能模塊進行區分
  2. 路由壓縮:koa-combine-routers
  3. 靜態資源處理:koa-static

koa-helment 安全頭

koa熱加載nodemon

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章