nodej框架——koa2基础使用

中文文档: 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)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、安装脚手架koa-generator 创建koa2项目 访问路径:http://localhost:3000/...
    BULL_DEBUG阅读 737评论 0 0
  • 首先,感谢 夕雅y的“❤️”。 上篇文章因为没有评论,我并不知道反响如何,不知道这种写作方式对于读者来说是否适合,...
    Qibing_Fang阅读 363评论 0 1
  • 前传 出于兴趣最近开始研究koa2,由于之前有过一些express经验,以为koa还是很好上手的,但是用起来发现还...
    little_short阅读 18,813评论 4 17
  • koa2框架笔记 Node.js是一一个异步的世界,官方API支持的都是callback 形式的异步编程模型,这会...
    wanminglei阅读 585评论 0 0
  • koa2框架笔记 Node.js是一一个异步的世界,官方API支持的都是callback 形式的异步编程模型,这会...
    wanminglei阅读 1,876评论 0 2