koa基礎使用
- 創建空文件夾koas
- 終端中進入該目錄執行npm init -y
- 安裝koa:npm install --save koa
- 創建index.js入口文件
const Koa = require('koa')
const app = new Koa()
app.use(async ctx => {
ctx.body = 'hello'
})
app.listen(3000)
- 執行node index.js
- 在瀏覽器中輸入:localhost:3000
koa-router使用
- 安裝依賴:npm install -S koa-router
- 重新編輯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)
- 執行node index.js
- 在瀏覽器中輸入:localhost:3000 頁面顯示hello
- 在瀏覽器中輸入:localhost:3000/api 頁面顯示hello api
koa開發RESTful接口
使用到的中間件
- 路由:koa-router
- 協議解析:koa-body
- 跨域處理:@koa/cors
使用上面的中間件
- 安裝依賴中間件:npm install koa-router koa-body @koa/cors -S
- 編輯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)
- 執行node index.js
- 在postman中測試localhost:3000/post 接口
路由路徑前綴設置
router.prefix('/api')
獲取get請求中的參數
ctx.request.query
使用koa-json優化返回的數據的格式
- 安裝依賴:npm install -S koa-json
- 使用
const json = require('koa-json')
app.use(json())
koa路由進階配置
開發目錄結構
- 按照功能模塊進行區分
- 路由壓縮:koa-combine-routers
- 靜態資源處理:koa-static
koa-helment 安全頭
koa熱加載nodemon