Koa 提供一个 Context 对象,表示一次对话的上下文(包括 HTTP 请求和 HTTP 回复)。通过加工这个对象,就可以控制返回给用户的内容。
Context.response.body
属性就是发送给用户的内容。
模块可以将多个中间件合成为一个
例子:
const compose = require('koa-compose'); const logger = (ctx, next) => { console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`); next(); } const main = ctx => { ctx.response.body = 'Hello World'; }; const middlewares = compose([logger, main]); app.use(middlewares); Koa2 路由的前缀
var router = new Router({ prefix: '/users'});router.get('/', ...); // responds to "/users"router.get('/:id', ...); // responds to "/users/:id"
异步处理写法
app.use(async (ctx, next) => { await next(); ctx.response.type = 'text/html'; ctx.response.body = 'Hello, koa2!
';});
Koa框架的路由和Get/Post请求的处理方法。 例子(一个简单的登陆逻辑)
const Koa = require('koa');const router = require('koa-router')();const bodyParser = require('koa-bodyparser');const app = new Koa(); router.get('/', async (ctx, next) => { ctx.response.body = ``;}); router.post('/signin', async (ctx, next) => { console.log('look',ctx.request.body); var name = ctx.request.body.name || '', password = ctx.request.body.password || ''; console.log(`signin with name: ${name}, password: ${password}`); if (name === 'koa' && password === '12345') { ctx.response.body = `Index
Welcome, ${name}!
`; } else { ctx.response.body = `Login failed!
`; }}); app.use(bodyParser());app.use(router.routes());app.listen(3000);console.log(`app started at port 3000...`);类似的,put、delete、head请求也可以由router处理。