Skip to content

js
const Koa = require('koa')

const app = new Koa()

// 如果 /login 是 GET,返回登录页
// 如果 /login 是 POST,做登录操作

const body = (ctx) => {
  return new Promise((resolve, reject) => {
    const ary = []
    ctx.req.on('data', chunk => ary.push(chunk))
    ctx.req.on('end', () => {
      resolve(Buffer.concat(ary).toString())
    })
  })
}

app
  .use(async (ctx, next) => {
    if (ctx.path === '/login' && ctx.method === 'GET') {
      ctx.body = `
        <form action="/login" method="post">
          <input type="text" name="username" />
          <input type="password" name="password" />
          <button>登录</button>
        </from>
      `
    } else {
      await next()
    }
  })
  .use(async (ctx, next) => {
    if (ctx.path === '/login' && ctx.method === 'POST') {
      ctx.set('Content-Type', 'text/html')
      // 如果其它地方要使用,又要解析一遍
      ctx.body = await body(ctx)
    } else {
      await next()
    }
  })

app.listen(3000)
js
app
  // 封装成中间件,一进来就解析
  .use(bodyParser())
  .use(async (ctx, next) => {
    if (ctx.path === '/login' && ctx.method === 'GET') {
      ctx.body = `
        <form action="/login" method="post">
          <input type="text" name="username" />
          <input type="password" name="password" />
          <button>登录</button>
        </from>
      `
    } else {
      await next()
    }
  })
  .use(async (ctx, next) => {
    if (ctx.path === '/login' && ctx.method === 'POST') {
      ctx.set('Content-Type', 'text/html')
      ctx.body = ctx.request.body
    } else {
      await next()
    }
  })

app.listen(3000)