Skip to content

middleware.js

javascript
const Koa = require('koa')
const app = new Koa()

const middleware = function async(ctx, next) {
  console.log(`this is a middleware!`)
  console.log(ctx.request.path)
  // next();
}

const middleware1 = function async(ctx, next) {
  console.log(`this is a middleware1!`)
  console.log(ctx.request.path)
  next()
  console.log(`this is a middleware1 ending!`)
}

const middleware2 = function async(ctx, next) {
  console.log(`this is a middleware2!`)
  console.log(ctx.request.path)
  next()
  console.log(`this is a middleware2 ending!`)
}

app.use(middleware1)
app.use(middleware2)
app.use(middleware)

app.listen(3000)

index.js

javascript
const Koa = require('koa')
const Router = require('koa-router')
const cors = require('@koa/cors')
const koaBody = require('koa-body')
const json = require('koa-json')

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

router.prefix('/api')

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

router.get('/api', (ctx) => {
  // console.log(ctx);
  // console.log(ctx.request);
  const params = ctx.request.query
  console.log(params)
  // ctx.body = "hello Api";
  ctx.body = {
    name: params.name,
    age: params.age,
  }
})

router.get('/async', async (ctx) => {
  ctx.body = await new Promise((resolve) => {
    setTimeout(() => {
      resolve('hello async 2s later')
    }, 2000)
  })
})

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(json({ pretty: false, param: 'pretty' }))
// request, method, respond
// api url function router
// ctx, async
app.use(router.routes()).use(router.allowedMethods())

app.listen(3000)

package.json

javascript
{
  "name": "resource",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@koa/cors": "^3.1.0",
    "koa": "^2.13.0",
    "koa-body": "^4.2.0",
    "koa-router": "^9.4.0"
  },
  "devDependencies": {
    "koa-json": "^2.0.2"
  }
}