中文文档: https://koa.bootcss.com/
github: https://github.com/koajs/koa
koa/router github:https://github.com/koajs/router
一、安装
$ npm install koa @koa/router @koa/cors -S
二、使用
const Koa = require('koa')
const cors = require('@koa/cors')
const Router = require('@koa/router')
const app = new Koa()
const router = new Router()
const basicMiddleware = async (ctx, next) => {
ctx.set('Access-Control-Allow-Origin', '*')
ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With')
ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS')
if (ctx.method === 'OPTIONS') {
ctx.body = 200
} else {
await next()
}
}
app.use(cors())
app.use(basicMiddleware)
router.get('/userinfo', async (ctx, next) => {
const {id} = ctx.query
// 数据库查询
if(xxx){
ctx.body = {username: 'admin', id: 0}
}else{
ctx.throw(500)
}
})
app.use(router.routes()).use(router.allowedMethods())
app.listen(3000)